【发布时间】: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<为常量,如bool operator<(const A& rhs) const;所写,您允许右侧为常量,但不允许左侧为常量。 -
我明白了。完全有道理。谢谢!
-
我和
std::sort有同样的问题,特别难解决,因为gcc没有检测到,llvm错误很神秘。重现错误的最小示例:rextester.com/TPDK32644
标签: c++ algorithm c++11 stl operator-overloading