gpt4 book ai didi

c++ - 将从 std::map 获取的 std::pair 引用传递给接受 std::pair 引用的函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:59 29 4
gpt4 key购买 nike

编辑:第一个问题的答案是使用 std::pair。关于第二个问题(标记为“奖励问题”)有什么想法吗?

使用以下代码:

#include <map>
#include <vector>

void foo(std::pair<int, int>& p) // EDIT: it needs to be non-const
{}

int main()
{
std::pair<int, int> p{1,2};
foo(p);
std::vector<std::pair<int, int>> v{{1,2}};
for (auto& element : v)
{
foo(element); // works fine
}

std::map<int, int> m{std::make_pair(1,2)};
//std::map<int, int> m2{{1,2}};
for (auto& element : m) // the problematic loop
{
foo(element);
}

return 0;
}

我在后面的 for 循环中使用 m 收到以下消息:

error: invalid initialization of reference of type 'std::pair&' from expression of type 'std::pair'

以及以下带有 m2 的地方:

error: invalid initialization of non-const reference of type 'std::pair&' from an rvalue of type 'std::pair'

这是为什么?

奖励问题:我发现非常奇怪的是,当 m2 的初始化没有被注释掉并且 for 循环保持不变(其中仍然有 m 并且 m2 从未使用过)时,错误消息从

error: invalid initialization of reference of type 'std::pair&' from expression of type 'std::pair'

error: invalid initialization of non-const reference of type 'std::pair&' from an rvalue of type 'std::pair'

我很想知道您对此的看法。我用 onlinegdb.com 测试了这段代码

最佳答案

The container makes the key const (这适用于所有关联容器):

value_type    std::pair<const Key, T>

所以应该是void foo(std::pair<int const, int>& p) .

关于c++ - 将从 std::map 获取的 std::pair 引用传递给接受 std::pair 引用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51285629/

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