gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:38:54 28 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 ,您需要在 map 的Key类型上重载operator<,因为这是 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/65729232/

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