使用类错误的映射,编译错误
Using map with class error, compile error
我有以下编译器错误,如何修复?
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
,您需要在映射的Key类型上重载operator<
,因为这就是映射将元素插入其底层容器的方式。
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>
。
您需要map
的比较函数。您可以创建比较ar
的两个实例的operator<
,也可以创建一个自定义函数并将其作为第三个模板参数传递。
前者的一个例子可能是:
class ar {
...
bool operator<(const ar& rhs) const {
return std::tie(a,b,c) < std::tie(rhs.a, rhs.b, rhs.c);
}
...
};
operator <
必须可用于键类型,或者您应该为映射构造函数提供一个比较函子。
相关文章:
- 用MacOS Mojave编译C++:致命错误:mpi.h:没有这样的文件或目录
- std::is_base_of表示ctor编译错误
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- Qt Cmake 错误编译"GuiSupportQt not found"
- Opengl 精度转换错误编译错误 E0415
- 库将ARM架构错误编译为架构X64
- RT 音频 Mac 错误 g++ 编译错误
- 错误编译Boost.log
- 错误编译QT创建者 / QT窗口小部件示例
- 错误编译MIPS32
- Visual Studio 2013 中的错误(编译和运行代码)
- 链接错误编译qt项目在visual 2010
- 无法用模板错误编译nsgmls
- 奇怪的错误.编译失败
- 如果有人调用c++中的方法,则强制错误(编译时)
- 来自autoconf测试的错误编译命令
- 时间限制超出错误C++编译
- SFML 2.3 和 CodeBlocks 错误编译