【问题标题】:Invalid operand to binary expression on std::max_elementstd::max_element 上二进制表达式的操作数无效
【发布时间】:2015-01-08 06:09:50
【问题描述】:

我正在尝试使用 std::max_element 来查找已定义结构的 std::forward_list 中的最大元素。下面是代码:

//.h file:
#include <unordered_map>
#include <forward_list>

// my structure: 
struct A
{
    uint8_t length;
    bool reverseMatch;

    bool operator<(const A& rhs);
    A() : length(0), reverseMatch(false) {}
};

using Alias = std::unordered_map<uint32_t, std::forward_list<A>>;

class B
{
    Alias data;

public:
    parse(string inputFilename);
    A getBestMatch(uint32_t lineNumber);
};

麻烦的功能:

//.cpp file
#include <sstream>
#include <algorithm>
#include <string>
#include "file.h"

bool A::operator<(const A& rhs)
{
    return (this->length < rhs.length);
}
A B::getBestMatch(uint32_t lineNumber)
{
    A ret;
    auto dataIter = this->data.find(lineNumber);
    if (dataIter != data.end())
    {
        ret = *(std::max_element(dataIter->second.begin(), dataIter->second.end()));//!!!ERROR!!!
    }
    return ret;
}

我得到的错误是“二进制表达式的无效操作数('const A' 和 'const A')”。我不确定为什么我的 operator

【问题讨论】:

  • 使operator&lt; 为常量,如bool operator&lt;(const A&amp; rhs) const; 所写,您允许右侧为常量,但不允许左侧为常量。
  • 我明白了。完全有道理。谢谢!
  • 我和std::sort有同样的问题,特别难解决,因为gcc没有检测到,llvm错误很神秘。重现错误的最小示例:rextester.com/TPDK32644

标签: c++ algorithm c++11 stl operator-overloading


【解决方案1】:

改为

bool operator<(const A& rhs) const;

正如 Igor 所说,这解决了问题。

【讨论】:

    【解决方案2】:

    问题是您的operator&lt; 是非常量的,但更好的是使其成为非成员,这具有使左右参数一致的副作用:

    bool operator<(const A& lhs, const A& rhs)
    {
        return (lhs.length < rhs.length);
    }
    

    你可以在你的标题中声明它,在类之外,像这样:

    bool operator<(const A& lhs, const A& rhs);
    

    有些人(包括我自己)喜欢在不需要私有访问时将这些函数保留在类之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多