小编SPA*_*SPA的帖子

为什么 const std::pair<K,V>& 在 std::map 上基于范围的循环中不起作用?

当访问的元素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)

c++ stdmap c++11 c++14

5
推荐指数
1
解决办法
156
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

stdmap ×1