我想知道为什么不能将STL映射与用户定义的类一起使用。当我编译下面的代码时,我收到以下神秘的错误消息。这是什么意思?此外,为什么仅在用户定义的类型中发生这种情况? (将原始类型用作键时可以使用。)
C:\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_function.h||In member function `bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Class1]':|
C:\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_map.h|338|instantiated from `_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = Class1, _Tp = int, _Compare = std::less, _Alloc = std::allocator >]'|
C:\Users\Admin\Documents\dev\sandbox\sandbox\sandbox.cpp|24|instantiated from here|
C:\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_function.h|227|error: no match for 'operator<' in '__x < __y'| ||=== Build finished: 1 errors, 0 warnings ===|
#include <iostream>
#include <map>
using namespace std;
class Class1
{
public:
Class1(int id);
private:
int id;
};
Class1::Class1(int id): id(id)
{}
int main()
{
Class1 c1(1);
map< Class1 , int> c2int;
c2int[c1] = 12;
return 0;
}
最佳答案
实际上,您不必为类定义operator<
。您还可以为其创建比较器函数对象类,并使用它来专门化std::map
。扩展您的示例:
struct Class1Compare
{
bool operator() (const Class1& lhs, const Class1& rhs) const
{
return lhs.id < rhs.id;
}
};
std::map<Class1, int, Class1Compare> c2int;
碰巧的是,
std::map
的第三个模板参数的默认值为 std::less
,它将委派给为您的类定义的operator<
(如果没有,则失败)。但是有时您希望对象可用作映射键,但实际上却没有任何有意义的比较语义,因此,您不想为此在类上提供operator<
从而使人们感到困惑。如果是这样,您可以使用上面的技巧。实现此目的的另一种方法是专门设置
std::less
:namespace std
{
template<> struct less<Class1>
{
bool operator() (const Class1& lhs, const Class1& rhs) const
{
return lhs.id < rhs.id;
}
};
}
这样做的好处是,默认情况下,它将由
std::map
选择,但是您不会将operator<
暴露给客户端代码。
关于c++ - 如何使用以用户定义类型为键的std::maps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61623555/