c++ - 为什么 const std::pair& 在 std::map 上基于范围的 for 循环不起作用?
问题描述
在基于范围的 for 循环std::map
中访问via的元素时,我得到了对地图中实际数据的引用。另一方面,使用不会引用const auto& entry
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;
}
输出:
foo 42 0x11a7eb0
foo 42 0x7ffec118cfc0
我知道std::map
value_type 是std::pair<const Key, T>
. 但我真的不明白在第二个基于范围的循环中发生了什么。
解决方案
std::map<K, V>::value_type
是std::pair<const K, V>
,不是std::pair<K, V>
(见cppreference)
#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;
for(const std::pair<const std::string, int>& entry : my_map)
std::cout << entry.first << ' ' << entry.second << ' ' << &(entry.second) << std::endl;
return 0;
}
示例输出:
foo 42 0x2065eb0
foo 42 0x7ffc2d536070
foo 42 0x2065eb0
您的第二个循环有效,因为它正在创建一个临时std::pair<std::string, int>
并将其绑定到您的参考(说明)。如果您尝试改用非常量引用,您会看到它失败(因为它不能绑定到临时引用):
std::pair<std::__cxx11::basic_string<char>, int>&
错误:从类型 ' ' 的表达式中对类型 'std::pair<const std::__cxx11::basic_string<char>, int>
'的引用的无效初始化
推荐阅读
- flask - 调用 render_template 之前的烧瓶预加载器
- sql - 是否可以将 SELECT 表达式重用到 RETURNING 表达式中?
- c++ - CPP-eclipse 中的调试器有时会死机
- javascript - 异步 npm 模块中的错误回调
- json - 如何在 microsoft graph 中添加更多 ccRecipients?
- r - 将字母向量拆分为大小相等的向量
- javascript - Discord.js - 让用户最后一次活动?
- html - 将html表导出到带有角度的css的excel
- java - 需要从列表中删除重复项
- javascript - JQuery 自动完成 - 显示多个值