当访问的元素std::map通过const auto& entry在一个范围基于for循环我到在地图中的实际数据的参考。使用const std::pair<K,V>&,另一方面也没有给于数据的引用std::map
考虑这个例子(用 gcc 7.4 编译,-std=c++14)
#include <map>
#include <string>
#include <iostream>
int main(void)
{
std::map<std::string, int> my_map {{"foo", 42}};
for(const auto& entry : my_map)
std::cout << entry.first << ' ' << entry.second << ' ' << &(entry.second) << std::endl;
for(const std::pair<std::string, int>& entry : my_map)
std::cout << entry.first << ' ' << entry.second << ' ' << &(entry.second) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
foo 42 …Run Code Online (Sandbox Code Playgroud)