使用带类错误的地图,编译错误 [英] Using map with class error, compile error
本文介绍了使用带类错误的地图,编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到以下编译器错误,该如何解决?
I have the following compiler error, how could I fix it?
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;
}
推荐答案
您需要 map
的比较功能.您可以创建 operator<
来比较 ar
的两个实例,也可以创建一个自定义函数并将其作为第三个模板参数传递.
You need a comparison function for the map
. You can either create operator<
that compares two instances of ar
, or you can create a custom function and pass it as the 3rd template parameter.
前者的一个例子可能是:
An example of the former might be:
class ar {
...
bool operator<(const ar& rhs) const {
return std::tie(a,b,c) < std::tie(rhs.a, rhs.b, rhs.c);
}
...
};
这篇关于使用带类错误的地图,编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文