STL MAP应该使用find()或[n] identifier来寻找map中的元素吗? [英] STL MAP should use find() or [n] identifier to find element in map?
本文介绍了STL MAP应该使用find()或[n] identifier来寻找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;
//单向
it = mymap.find('b');
cout<< (* it).second<<< endl;
//另一种方式
cout<< mymap ['b']<< endl;
return 0;
}
提前感谢!
$ <$> $ <$> $ <$>解决方案 strong>如果键不存在,则在地图中创建新元素,更重要的是,这意味着您可以使用
find
查看 这当然意味着你应该检查
的返回值。 code> find 。通常它是这样的: void某处(const std :: map< K,T& ; key)
{
auto it = mymap.find(key);
if(it == mymap.end()){/ * not found! * /}
else {do_something_with(it-> second); }
}
I am confused which is more efficient?
As we can access map directly, why do we need to use find?
I just need to know which way is more efficient.
#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;
}
thanks in advance! :)
解决方案
Using find
means that you don't inadvertently create a new element in the map if the key doesn't exist, and -- more importantly -- this means that you can use find
to look up an element if all you have is a constant reference to the map.
That of course means that you should check the return value of find
. Typically it goes like this:
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); }
}
这篇关于STL MAP应该使用find()或[n] identifier来寻找map中的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文