可能的复制品:
在 STL 映射中,使用 map: : insert 比[] ? 更好吗
我在想,当我在 map 中插入元素时,推荐的方法是什么
map[key] = value;
或者
map.insert(std::pair<key_type, value_type>(key, value));
我做了以下快速测试:
#include <map>
#include <string>
#include <iostream>
class Food {
public:
Food(const std::string& name) : name(name) { std::cout << "constructor with string parameter" << std::endl; }
Food(const Food& f) : name(f.name) { std::cout << "copy" << std::endl; }
Food& operator=(const Food& f) { name = f.name; std::cout << "=" << std::endl; return *this; }
Food() { std::cout << "default" << std::endl; }
std::string name;
};
int main() {
std::map<std::string, Food> m0;
/*
1) constructor with string parameter
2) copy
3) copy
4) copy
*/
m0.insert(std::pair<std::string, Food>("Key", Food("Ice Cream")));
/*
1) constructor with string parameter
2) default
3) copy
4) copy
5) =
*/
// If we do not provide default constructor.
// C2512: 'Food::Food' : no appropriate default constructor available
m0["Key"] = Food("Ice Cream");
}
insert
,会涉及到较少值的函数调用。那么,使用 insert
是一种推荐的方法吗?I know that insert
doesn't overwrite existence key value pair, but map[key] = value
does. However, is this the only factor I take into consideration, when try to choose among the both?
怎么样