当关乎效率时应该在map::operator[]和map-insert之间仔细选择
假设有一个支持默认构造函数和赋值构造函数的类:
class Widget
{
public:
Widget() {}
Widget(int) {}
const Widget& operator=(int) {}
};
map<int, Widget> map;
map[0] = 0;
map[1] = 1;
map[2] = 2;
书上说,这种情况下使用operator[]操作的map,会先创建一个Widget临时变量,随后析构这个临时变量,最后进行一个赋值操作。
实际上根据我的测试,个人认为临时变量以已经被移动构造优化了。
在map操作最重要的应该是,key是否存在,然后进行所需要的操作,这里给出一个简单的判断key存在的示例:
//每个map必须的key值都需要在这里声明
enum class MapParam
{
Apple,
Lemon,
Peach
};
using paramMap = map<MapParam, string>;
//判断是否存在某个key 这个key取值于MapParam
template<typename Key>
bool isExistParam(paramMap thisMap, Key key)
{
return thisMap.find(key) != thisMap.end();
}
//获取某个key下的value
template<typename ReturnType, typename Key>
ReturnType getParam(paramMap thisMap, Key key)
{
auto constIter = thisMap.find(key);
if (constIter == thisMap.end())
{
//throw
}
return constIter->second;
}
paramMap thisMap;
thisMap.insert(make_pair<MapParam, string>(MapParam::Apple, "Apple"));
thisMap.insert(make_pair<MapParam, string>(MapParam::Lemon, "Lemon"));
if (isExistParam(thisMap, MapParam::Apple))
{
cout << getParam<std::string>(thisMap, MapParam::Apple) << endl;
}
if (isExistParam(thisMap, MapParam::Lemon))
{
cout << getParam<std::string>(thisMap, MapParam::Lemon) << endl;
}
if (isExistParam(thisMap, MapParam::Peach))
{
cout << getParam<std::string>(thisMap, MapParam::Peach) << endl;
}
这个map没有peach这个key所以打印:
Apple
Lemon