如何使用 std::maps 和用户定义的类型作为键?

新手上路,请多包涵

我想知道为什么我不能将 STL 映射与用户定义的类一起使用。当我编译下面的代码时,我收到以下神秘的错误消息。这是什么意思?另外,为什么它只发生在用户定义的类型上? (原始类型在用作键时是可以的。)

C:\MinGW\bin..\lib\gcc\mingw32\3.4.5……..\include\c++\3.4.5\bits\stl_function.h||在成员函数`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|从`_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|从这里实例化|

C:\MinGW\bin..\lib\gcc\mingw32\3.4.5……..\include\c++\3.4.5\bits\stl_function.h|227|error: no match for ‘operator <’ 在 ‘__x < __y’| ||=== 构建完成:1 个错误,0 个警告 ===|

 #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;
}

原文由 unknown 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 564
1 个回答

如果您只是添加,您的示例 适用于 C++20

 auto operator<=>(Class1 const &) const = default;

到你的班级。

原文由 user541686 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题