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 ,它将委派给为您的类定义的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/

相关文章:

c++ - 重载所有基本整数类型是否足以捕获所有整数?

python - Pandas Groupby 字典列表到一个字典

iOS parse.com 推送错误

c++ - 如何到达 2d std::vector (`std::vector< std::vector<T>>` ) 的第 N 个元素?

c++ - 如何修改不同类型列表中的元素?

c++ - 在 C++ 中合并两个 boost 侵入集?

c++ - 为什么我在 Microsoft Visual C++ 2010 Express 中收到此消息

c++ - 在 std::set 或 std::unordered_set 上保留插入顺序

c++ - 如何锁定由属于 2 个不同类的 2 个线程修改的数据结构

javascript - 如何打印数组中列出的字典中的键和值,javascript