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

标签 c++ dictionary stl containers stdmap

我想知道为什么我不能将 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 , 这将委托(delegate)给 operator<为您的类(class)定义(如果没有则失败)。但有时您希望对象可用作映射键,但实际上并没有任何有意义的比较语义,因此您不想通过提供 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/1102392/

相关文章:

c++ - 具有类型 'const CompareVPtrs' 的表达式将丢失一些 const-volatile 限定符以便调用

c++ - 为什么没有 set_union 等使用容器类型而不是迭代器的便利函数?

c++ - 应用程序中的全局计数器 : bad practice?

Python 字典理解 : assign value to key, 其中值是一个列表

python - 无法在 python 中删除某些嵌套的 JSON 对象

c++ - 删除默认构造函数会导致 STL 容器中的默认分配器出现问题

c++ - 带有命名对象的复制构造函数

c++ - std::map operator[] 并自动创建新对象

php - c++ 和 php 中的 openssl 加密

python - 计算并删除键中的重复项,同时保留值