c++ - STL MAP 应该使用 find() 或 [n] 标识符在 map 中查找元素?

标签 c++ stl map upperbound

我很困惑哪个更有效率?

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

相关文章:

java - try 和 catch block 不是捕获异常,而是给出无穷大的结果

c++ - 使用strncpy复制tcp流会导致故障吗?

c++ - 用于类似区域/竞技场分配的 STL 容器

c++ - 在 float 中实现 pow() 函数的最有效方法

c++ - 动态内存分配,堆,间接,NULL

c++ - std::map 中的内存分配

c++ - “no match for ' operator< '” 尝试插入到 std::set 时

apache - Apache Hive与法线贴图减少

c++ - 如何对 std::map 中的所有值求和?

Android 和 XML map