The*_*One 12 c++ stl hashmap map
index重载运算符和std :: map的insert方法调用之间有什么区别?
即:
some_map["x"] = 500;
Run Code Online (Sandbox Code Playgroud)
与
some_map.insert(pair<std::string, int>("x", 500));
Run Code Online (Sandbox Code Playgroud)
pxb*_*pxb 22
我相信insert()不会覆盖现有值,并且可以通过测试返回的迭代器/对值中的bool值来检查操作的结果
对下标运算符[]的赋值只会覆盖那里的任何内容(如果已经没有那个,则插入一个条目)
如果您不期望该行为并且不适应它,则insert和[]运算符中的任何一个都可能导致问题.
例如插入:
std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap.insert( std::make_pair( 100, s1 ) ); // inserted
intMap.insert( std::make_pair( 100, s2 ) ); // fails, s2 not in map, could leak if not tidied up
Run Code Online (Sandbox Code Playgroud)
和[]运算符:
std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap[ 100 ] = s1; // inserted
intMap[ 100 ] = s2; // inserted, s1 now dropped from map, could leak if not tidied up
Run Code Online (Sandbox Code Playgroud)
我认为这些是正确的,但没有编译它们,所以可能有语法错误
对于a map,previous(operator[])表达式将始终用新提供的值替换键值对的值部分.如果尚未存在新的键值对,则将插入新的键值对.
相反,insert如果地图中不存在与提供的关键部分的键值对,则仅插入新的键值对.
除了map::operator[]将替换现有值的事实之外,operator[]map ::还将在替换发生之前创建要替换的默认现有值并将其添加到映射中(map::operator[]()调用必须返回对某物的引用)。对于制造昂贵的物品,这可能是性能问题。
请参阅“第24项:仔细选择之间map::operator[]和map::insert时效率是非常重要的”,在斯科特迈尔斯有效的STL。