gpt4 book ai didi

c++ - 使用带有类错误的 map ,编译错误

转载 作者:行者123 更新时间:2023-11-28 03:22:54 24 4
gpt4 key购买 nike

我有以下编译器错误,我该如何解决?

error:  instantiated from `_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = ar, _Tp = int, _Compare = std::less<ar>, _Alloc = std::allocator<std::pair<const ar, int> >]' 

这是代码:

#include <map>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstdlib>

using namespace std;

class ar {
public:
int a;
int b;
int c;
public:
ar() : a(0), b(0), c(0) {}
};

int main() {
map<ar, int> mapa;
ar k;
k.a = 6;
k.b = 1;
k.c = 0;
mapa[k] = 1;

//system("pause");
return 0;
}

最佳答案

对于 std::map 你需要重载 operator<在 map 的键类型上,因为这是 map 将元素插入其底层容器的方式。

class ar { 
public:
int a;
int b;
int c;
public:
ar() : a(0), b(0), c(0) {}
bool operator<(const ar& other) const;
};

bool ar::operator< (const ar& other) const // note the function has to be const!!!
{
return (other.a < a) && (other.b < b) && (other.c < c); // or some such ordering
}

重载时operator< , 以类似的方式也重载 operator> 是个好主意.

关于c++ - 使用带有类错误的 map ,编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14967757/

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