std::max_element 上二进制表达式的无效操作数 [英] Invalid operand to binary expression on std::max_element

查看:65
本文介绍了std::max_element 上二进制表达式的无效操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use std::max_element to find the largest element in a std::forward_list of a defined structure. Here is the code below:

//.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')".我不知道为什么我的操作员<超载在这里有问题.我还需要定义其他操作数吗?如果是这样,为什么?我读过的所有文档都指出 std::max_element 使用 <操作员.谢谢!

The error that I'm getting is "Invalid operands to binary expression ('const A' and 'const A')". I'm not sure why my operator< overload is having issues here. Do I need to define other operands as well? If so, why? All documentation that I have read states that std::max_element uses the < operator. Thanks!

推荐答案

改为

bool operator<(const A& rhs) const;

正如 Igor 上面所说的那样解决了这个问题.

as Igor stated above and that fixed the issue.

这篇关于std::max_element 上二进制表达式的无效操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆