我很困惑哪个更有效率?
既然可以直接访问map,为什么还要用find呢?
我只需要知道哪种方式更有效。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
map<char,int>::iterator it;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
//one way
it=mymap.find('b');
cout << (*it).second <<endl;
//another way
cout << mymap['b'] <<endl;
return 0;
}
提前致谢! :)
最佳答案
使用 find
意味着如果键不存在,您不会无意中在 map 中创建一个新元素,更重要的是,这意味着您可以使用 find
来查找元素,如果您拥有的只是对 map 的常量 引用。
这当然意味着您应该检查find
的返回值。通常它是这样的:
void somewhere(const std::map<K, T> & mymap, K const & key)
{
auto it = mymap.find(key);
if (it == mymap.end()) { /* not found! */ }
else { do_something_with(it->second); }
}
关于c++ - STL MAP 应该使用 find() 或 [n] 标识符在 map 中查找元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10582089/