I have a class roughly defined like below. Among others, it has a < comparison operator.
class DictionarySearchItem {
public:
DictionarySearchItem();
double relevance() const;
bool operator<(const DictionarySearchItem& item) { return relevance() > item.relevance(); }
};
typedef std::vector<DictionarySearchItem> DictionarySearchItemVector;
I then use the class this way:
DictionarySearchItemVector searchItems;
for (unsigned i = 0; i < entries.size(); i++) {
// ...
// ...
DictionarySearchItem item;
searchItems.push_back(item);
}
However when I try to sort the vector:
std::sort(searchItems.begin(), searchItems.end());
I’m getting the following compilation error with MinGW.
/usr/include/c++/4.2.1/bits/stl_algo.h:91: erreur : passing 'const hanzi::DictionarySearchItem' as 'this' argument of 'bool hanzi::DictionarySearchItem::operator<(const hanzi::DictionarySearchItem&)' discards qualifiers
I don’t quite understand what is incorrect with my code and the error message is not clear to me. The same code compiles fine with MSVC2008. Any idea what could be the issue?
You need to make the less-than operator
const:The reason is probably that
sortrelies on the fact that elements being compared cannot change as a result of the comparison. This can be enforced by having both sides of the<comparison be const, which means the operator has to be const, as well as it’s argument.