gpt4 book ai didi

c++ - 为什么 std::map 上基于范围的 for 循环中的 const std::pair& 不起作用?

转载 作者:行者123 更新时间:2023-12-01 13:34:02 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Using find_if on map containing shared_ptr increases ref count

(1 个回答)


1年前关闭。




访问 std::map 的元素时通过 const auto& entry基于范围的 for 循环 我得到了对 map 中实际数据的引用。使用 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_typestd::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;
}
Example output :
foo 42 0x2065eb0
foo 42 0x7ffc2d536070
foo 42 0x2065eb0
您的第二个循环有效,因为它正在创建一个临时 std::pair<std::string, int>并将其绑定(bind)到您的引用( explanation )。如果您尝试改用非常量引用,您会看到它失败(因为它不能绑定(bind)到临时引用):

error: invalid initialization of reference of type 'std::pair<std::__cxx11::basic_string<char>, int>&' from expression of type 'std::pair<const std::__cxx11::basic_string<char>, int>'

关于c++ - 为什么 std::map 上基于范围的 for 循环中的 const std::pair<K,V>& 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62863726/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com