通常,如果您执行查找和插入操作,那么您希望保留(并检索)旧值(如果它已经存在)。如果您只想覆盖任何旧值,map[foo_obj]="some value" 会这样做。
以下是获取旧值或插入新值(如果它不存在)的方法,只需一次地图查找:
typedef std::map<Foo*,std::string> M;
typedef M::iterator I;
std::pair<I,bool> const& r=my_map.insert(M::value_type(foo_obj,"some value"));
if (r.second) {
// value was inserted; now my_map[foo_obj]="some value"
} else {
// value wasn't inserted because my_map[foo_obj] already existed.
// note: the old value is available through r.first->second
// and may not be "some value"
}
// in any case, r.first->second holds the current value of my_map[foo_obj]
这是一个非常常见的习语,您可能想要使用辅助函数:
template <class M,class Key>
typename M::mapped_type &
get_else_update(M &m,Key const& k,typename M::mapped_type const& v) {
return m.insert(typename M::value_type(k,v)).first->second;
}
get_else_update(my_map,foo_obj,"some value");
如果你有一个昂贵的 v 计算,如果它已经存在,你想跳过它(例如 memoization),你也可以概括它:
template <class M,class Key,class F>
typename M::mapped_type &
get_else_compute(M &m,Key const& k,F f) {
typedef typename M::mapped_type V;
std::pair<typename M::iterator,bool> r=m.insert(typename M::value_type(k,V()));
V &v=r.first->second;
if (r.second)
f(v);
return v;
}
例如在哪里
struct F {
void operator()(std::string &val) const
{ val=std::string("some value")+" that is expensive to compute"; }
};
get_else_compute(my_map,foo_obj,F());
如果映射类型不可默认构造,则让 F 提供默认值,或向 get_else_compute 添加另一个参数。