gpt4 book ai didi

c++ - 如何将结构作为键插入 map ?

转载 作者:太空狗 更新时间:2023-10-29 19:37:10 25 4
gpt4 key购买 nike

在从第一个 insert 行中删除注释字符后,我收到以下代码的编译错误。我无法将结构插入到映射中,但可以插入整数。

# include <iostream>
# include <map>

using namespace std;

struct node
{int test;} temp;

int main()
{
temp.test = 24;
int test = 30;
map<node, bool> mymap1;
map<int, bool> mymap2;
//mymap1.insert(make_pair(temp, true));
mymap2.insert(make_pair(test, true));
return 0;
}

如何修复错误?

最佳答案

对于用作映射键的类型,它必须是有序的。实际上,这意味着 operator<必须为类型定义。如果您定义了全局 operator<(const node&, const node&) ,这应该可以正常工作;即,

bool operator<(const node& n1, const node& n2) {
return n1.test < n2.test;
}

关于c++ - 如何将结构作为键插入 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7112698/

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