向地图分配值的最有效方法 [英] Most efficient way to assign values to maps

查看:89
本文介绍了向地图分配值的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法为地图分配值最有效?还是它们都针对同一代码进行了优化(在大多数现代编译器上)?

Which way to assign values to a map is most efficient? Or are they all optimized to the same code (on most modern compilers)?

   // 1) Assignment using array index notation
   Foo["Bar"] = 12345;

   // 2) Assignment using member function insert() and STL pair
   Foo.insert(std::pair<string,int>("Bar", 12345));

   // 3) Assignment using member function insert() and "value_type()"
   Foo.insert(map<string,int>::value_type("Bar", 12345));

   // 4) Assignment using member function insert() and "make_pair()"
   Foo.insert(std::make_pair("Bar", 12345));

(我知道我可以进行基准测试并检查编译器的输出,但是现在出现了这个问题,我手边只有我的手机...呵呵)

(I know I could benchmark and check compiler output, but this question arose now and the only thing I have close at hand is my mobile phone... hehe)

推荐答案

首先,[]insert之间存在语义差异:

First, there are semantic differences between [] and insert:

  • []替换旧值(如果有)
  • insert忽略新值(如果已经存在旧值)
  • [] will replace the old value (if any)
  • insert will ignore the new value (if an old value is already present)

因此,将两者进行比较通常是没有用的.

therefore comparing the two is useless in general.

关于插入版本:

  • std::map<std::string, int>::value_type std::pair<std::string const, int>,所以3和4之间没有(重要)差异
  • std::make_pair("Bar", 12345)std::pair<std::string, int>("Bar", 12345)便宜,因为std::string类型是完全成熟的类,可以对副本进行操作,而"Bar"只是字符串文字(因此只是指针副本);但是,由于最后您确实需要创建std::string ...,这将取决于编译器的质量
  • std::map<std::string, int>::value_type is std::pair<std::string const, int> so no (important) difference between 3 and 4
  • std::make_pair("Bar", 12345) is cheaper than std::pair<std::string, int>("Bar", 12345) because the std::string type is a full fledged class with operations to do on copy and "Bar" is just a string literal (thus just a pointer copy); however since at the end you do need to create the std::string... it will depend on the quality of your compiler

通常,我会建议:

  • []用于更新
  • insert(std::make_pair())用于忽略重复项
  • [] for updating
  • insert(std::make_pair()) for ignoring duplicates

std::make_pair不仅简短,而且还遵守DRY准则:请勿重复自己.

std::make_pair is not only shorter, it also respects the DRY guideline: Don't Repeat Yourself.

为了完整起见,最快(也是最简单)的方法是 emplace (C ++ 11已启用):

For completeness though, the fastest (and easiest) would be emplace (C++11 enabled):

map.emplace("Bar", 12345);

它的行为是insert的行为,但是它就地构造了新元素.

Its behavior is that of insert, but it constructs the new element in-place.

这篇关于向地图分配值的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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