map::insert() will only create:
using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(std::make_pair(key,value));
if ( ! res.second ) {
cout << "key " << key << " already exists "
<< " with value " << (res.first)->second << endl;
} else {
cout << "created key " << key << " with value " << value << endl;
}
For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read
map[key] = value.
本文详细介绍了如何使用C++标准库中的map::insert方法来插入元素,并通过示例代码展示了如何判断键是否已存在以及如何处理已存在的键值对。此外,还提供了更简洁的赋值操作方式。
1895

被折叠的 条评论
为什么被折叠?



