c++ - std::map 中的用户定义类:二进制表达式的无效操作数

标签 c++ c++11

我想使用一个类作为 std::map 中的键。

std::map<Type, value> collection;

虽然我定义了operator< , key 不被接受:Invalid operands to binary expression ('const Type' and 'const Type') .

class Type {
public:
    inline bool operator< (const Type& rhs) { /* ... */ }

为什么会这样?

最佳答案

您必须定义您的 operator<作为

inline bool operator< (const Type& rhs) const { /* ... */ }

因为 map 存储 const key内部。


为了扩展一点,我还建议(就像评论中的 dyp 一样)尽可能使用非成员运算符重载。他们有各种各样的优势。我不会在这里列出它们,因为已经有关于优势/差异的很好的信息,让我将您链接到 Operator overloading : member function vs. non-member function? .

关于c++ - std::map 中的用户定义类:二进制表达式的无效操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438363/

相关文章:

c++ - 随机 float 生成

c++ - 如何使用 C++ 检查 <wstring> 是否以某个字符串开头

c++ - 带有 lambda 自定义删除器的 std::unique_ptr 无法编译

c++ - 在 C++11 中确定泛型返回类型时出错

c++ - 我如何构造一个仿函数以用于像 boost 的 brent_find_minima 这样的算法?

c++ - Windows 7 中的 Oleaut32.lib 在哪里?

c++ - 置换成本

c++ - 使用 C++11 future :std::async 崩溃的嵌套调用:编译器/标准库错误?

c++ - C<T> 派生自T,安全吗?

c++ - 使用迭代器 C++ 打印 std::list 的元素