#include <iostream>
#include <vector>
#include <algorithm>
class MyData
{
public:
int m_iData;
bool operator<(MyData rhs) { return m_iData < rhs.m_iData; }
};
int main ()
{
std:: vector <MyData> myvector(2, MyData() );
myvector[0].m_iData=2; myvector[1].m_iData=4;
std::sort(myvector.begin(), myvector.end());
}
Attempting to compile this gives:
error: passing 'const MyData' as 'this' argument of 'bool MyData::operator<(MyData)'
discards qualifiers
The comparison operator will be called on a const-reference of a class instance, so it must be declared as a const member function.
It is also good practice to pass the argument by const-reference rather than by value, although it doesn't make much of a difference for your simple class:
bool operator<(const MyData & rhs) const { return m_iData < rhs.m_iData; }
// ^^^^^^^^^^^^^^ ^^^^^
// if you like mandatory
It is generally highly recommended to declare all member functions constant which do not mutate your object. This does not only communicate your intention and design, but it would also not be possible otherwise to use those functions on constant objects or references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With