标准::max_element 上二进制表达式的操作数无效
Invalid operand to binary expression on std::max_element
我正在尝试使用 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);
有些人(包括我自己)在不需要私有访问时更喜欢将此类函数保留在类之外。
相关文章:
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- 二进制表达式的操作数无效 - 使用 for 和迭代器
- 错误:参数中无效地使用了无效表达式
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- 二进制表达式 cout 问题的无效操作数
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 在c++std::函数的上下文中无效使用void表达式
- C++ 解决方法:"从类型"B*"的表达式初始化类型"C*&"的引用无效"
- 二进制表达式的操作数无效?
- 二进制表达式的操作数无效("常量字符*"和"常量字符*")
- 如何修复"二进制表达式的无效操作数"?
- 没有变量声明为函数,但错误:二进制表达式的操作数无效
- 如何修复此错误:二进制表达式的操作数无效("std::vector<double>"和"double")?
- 正则表达式 & 无效的空指针表达式
- Regex表达式无效
- 使用 std::vector 时抽象类类型"Shape"的新表达式无效错误
- 在for循环的范围中,std::valarray的范围表达式无效
- 抽象类类型的新表达式无效
- 使用优先级队列时C++调试断言失败,表达式:无效堆