STL MAP 应该使用 find() 或 [n] 标识符来查找地图中的元素吗?

2022-01-07 00:00:00 c++ map stl upperbound

我很困惑哪个更有效?

既然可以直接访问map,为什么还要用find?

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;
}

提前致谢!:)

推荐答案

使用 find 意味着您不会无意中创建地图中的新元素,如果键不存在,而且――更重要的是――这意味着你可以使用 find 来查找元素,如果你只有一个对地图的常量引用.

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.

这当然意味着你应该检查find的返回值.通常是这样的:

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); }
}

相关文章