以下是地图查找和插入用例的几个示例,您有时想要处理已经存在的项目的情况,查看旧值是什么等。
class Foo
{
// Use a typedef so we can conveniently declare iterators
// and conveniently construct insert pairs
typedef map<int, std::string> IdMap;
IdMap id_map;
// A function that looks up a value without adding anything
void one(int id)
{
IdMap::iterator i = id_map.find(id);
// See if an entry already exists
if (i == id_map.end())
return; // value does not exist
// Pass the string value that was stored in the map to baz
baz(i->second);
}
// A function that updates an existing value, but only if it already exists
bool two(int id, const std::string &data)
{
IdMap::iterator i = id_map.find(id);
if (i == id_map.end())
return false;
i->second = data;
return true;
}
// A function that inserts a value only if it does NOT already exist
// Returns true if the insertion happened, returns false if no effect
bool three(int id, const std::string &data)
{
return id_map.insert(IdMap::value_type(id, data)).second;
}
// A function that tries to insert if key doesn't already exist,
// but if it does already exist, needs to get the current value
void four(int id, const std::string &data)
{
std::pair<IdMap::iterator,bool> i =
id_map.insert(IdMap::value_type(id, data));
// Insertion worked, don't need to process old value
if (i->second)
return true;
// Pass the id to some imaginary function that needs
// to know id and wants to see the old string and new string
report_conflict(id, i->first->second, data);
}
};
出于懒惰或无知,程序员经常对 进行多次冗余调用operator[]
,或者一次调用find
然后对 进行冗余调用operator[]
,或者对 调用find
然后对 进行冗余调用。insert
如果您了解地图的语义,那么有效地使用地图是非常容易的。