C++备忘录065:*map的key值是const

#include <map>
#include <type_traits>

double foo(int key) {
    const std::map a = {
        std::pair<int, double>{1, .1},
        std::pair<int, double>{2, .2},
    };

    static_assert(std::is_same_v<decltype(a)::value_type, std::pair<const int, double>>);
    for (const std::pair<int, double> &i : a) {
        if (i.first == key) {
            return i.second;
        }
    }

    return .0;
}

这里的for循环中,每次循环都会产生map中对应值的拷贝,因为map中的值类型是std::pair<const int, double>,而不是std::pair<int, double>

C++ Insights中对应的语句如下

for(; __begin1.operator!=(__end1); __begin1.operator++()) {
  const std::pair<int, double> & i = std::pair<int, double>(__begin1.operator*());
  if(i.first == key) {
    return i.second;
  }   
}

确实生成了多余的拷贝

如果把for循环中的类型改成std::pair<const int, double>,或者直接用auto的话,C++ Insights就变成了

for(; __begin1.operator!=(__end1); __begin1.operator++()){
  const std::pair<const int, double> & i = __begin1.operator*();
  if(i.first == key) {
    return i.second;
  }
}

成了引用,避免了无谓的性能损失

发布了68 篇原创文章 · 获赞 0 · 访问量 677

猜你喜欢

转载自blog.csdn.net/u011241498/article/details/104097681
今日推荐