• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Why does std::set work with my free function operator

Resolved: Why does std::set work with my free function operator<, but not my class member function operator 0

By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

If I use the free function operator <, my program works. If I use the implementation inside the class, I get a compiler error. Why doesn’t implementing this as a class member function work?
Part of the error I get:

usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_function.h:386:20: error: invalid operands to binary expression (‘const my’ and ‘const my’)
{ return __x < __y; } ~~~ ^ ~~~ [/code]

The code :

class my{

public:
int a;
double b;
my(int p){
a=p;
b=0;
}
bool operator> (const my other){
return this->a > other.a;
}
bool operator < (const my other) { return this->a < other.a; } }; // bool operator < ( const my othe2,const my other) { // return othe2.a < other.a; // } int main(){ set s={10,5};
s.emplace(8);
s.emplace(-8);

for(auto t:s){
cout<

Answer:

They should be overloaded with const directive. Otherwise, the non const operators can’t be applied to const my whatever a.k.a. std::set<my>::key_type whatever inside std::set. Add

bool operator> (const my& other) const {
return this->a > other.a;
}
bool operator < (const my& other) const { return this->a < other.a; } [/code]

Additionally other should be passed by reference const my& other.

If you have better answer, please add a comment about this, thank you!

c++ containers operators
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Getting ‘502 Bad Gateway’ while deploying Springboot app in EKS

24/03/2023

Resolved: Why is NGINX’s $request_uri empty?

24/03/2023

Resolved: How to convert Java bytecode to Webassembly using CheerpJ compiler

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.