vendredi 25 août 2023

Why operator < overload isn't recognized

I have a struct that I defined as following:

struct MyStruct {
  string key;
  MyStruct(const string& k) :key(k) {}
  bool operator<(const MyStruct& p1) {return this->key < p1.key; }
};

I also created a v = vector<MyStruct> and now I want to sort this vector based on the key values in each MyStruct by calling std::sort(v.begin(), v.end())

However, the program failed to compile with the following error message:

error: invalid operands to binary expression ('const MyStruct' and 'const MyStruct')

I searched for < overloading and found the solution by defining it as non member function. But I wonder what went wrong in my code? It seems that the < overload wasn't recognized by the sort?

Any help or reference is appreciated. Thank you!

Aucun commentaire:

Enregistrer un commentaire