可能是重复问题:
在 STL map 中,使用 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
是推荐的方法吗? - 当使用
map [key] = value
方式时,为什么需要默认构造函数?
我知道 insert
不会覆盖已存在的键值对,但 map [key] = value
会。然而,在尝试从两者中选择时,这是否是我考虑的唯一因素呢?
如何处理以下因素?
- 性能
- 值默认构造函数的可用性
- ???
insert
,否则请使用map[key] = value
。 - Ioan Paul Pirau