STL MAP 应该使用 find() 或 [n] 标识符来查找地图中的元素吗? [英] STL MAP should use find() or [n] identifier to find element in map?

查看:16
本文介绍了STL MAP 应该使用 find() 或 [n] 标识符来查找地图中的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑哪个更有效?

既然可以直接访问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); }
}

这篇关于STL MAP 应该使用 find() 或 [n] 标识符来查找地图中的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆