标准::max_element 上二进制表达式的操作数无效

Invalid operand to binary expression on std::max_element

本文关键字:表达式 无效 二进制 操作数 max element 标准      更新时间:2023-10-16

我正在尝试使用 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')"。我不确定为什么我的操作员<过载在这里出现问题。我还需要定义其他操作数吗?如果是这样,为什么?我读过的所有文档都指出><运算符。谢谢!>

更改为

bool operator<(const A& rhs) const;

正如伊戈尔上面所说,这解决了这个问题。

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

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

您可以在类外部的标头中声明它,如下所示:

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

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