唉,STL函数和容器并不总能达到您所期望的。这里有两个通用版本,第一个更喜欢你上面的代码:
template<class Map>
inline typename Map::iterator ForceInsert1(
Map& m,
const typename Map::key_type& k,
const typename Map::data_type& d)
{
typename Map::iterator it = m.insert(
typename Map::value_type(k, d)).first;
it->second = d; // only necessary if the key already exists
return it;
}
template<class Map>
inline typename Map::iterator ForceInsert2(
Map& m,
const typename Map::key_type& k,
const typename Map::data_type& d)
{
typename Map::iterator it = m.find(k);
if(it != m.end())
{
it->second = d;
}
else
{
it = m.insert(typename Map::value_type(k, d)).first;
}
return it;
}
typedef std::map<int, int> MyMap;
void Foo(MyMap& myMap)
{
ForceInsert1(myMap, 42, 100);
ForceInsert2(myMap, 64, 128);
}
请注意,地图的价值类型不'对' ,而是'pair '。 –
2012-04-13 20:19:07
插入或编辑,你想要哪一个?很明显,你已经有了一个插入的单线程,那么问题到底是什么? – 2012-04-13 20:20:17
我相信你找到了最有效的方法。如果你只是不喜欢它的外观,实现一个“替换”功能,结合这两个步骤,但即使这样做将按照你的例子来实现。 – Chad 2012-04-13 20:20:40