Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors when creating set

Tags:

c++

set

I would like to know why i am unable to create a set. I am getting the following error

Here is my codes.

Point.cpp My Point class

bool Point::operator<(const Point& p2)const {
return p21.length < p2.getScalarValue();
}

bool Point::operator>(const Point p2) {
bool result;
result = length > p2.getScalarValue();
return result;

}

and in my main.cpp

set<Point> s_p2;
Point tempp2;
s_p2.insert(tempp2);

After following your inputs, i have edited the codes and i have the following error

Point.cpp:56:46: error: passing ‘const Point’ as ‘this’ argument of ‘double Point::getScalarValue()’ discards qualifiers [-fpermissive]

Is this because i got two comparing statements ?

like image 774
M.A Avatar asked Dec 17 '25 23:12

M.A


1 Answers

There is no std::set::insert overload that takes a bool as second paramater. You can insert like this:

s_p2.insert(tempp2);

Your operator< could be improved too, by making it a const method, taking a const reference parameter:

class Point {
  // as before
  bool operator<(const Point& p) const;
};  //                            ^ here, const method

bool Point::operator<(const Point& p2) const {
  return length < p2.length;
}

You could also choose to make it a non-member function:

bool operator<(const Point& lhs, const Point& rhs) {
  return lhs.getScalarValue() < rhs.getScalarValue();
}

This has the advantage of being completely symmetric to LHS and RHS. This matters if you have implicit conversions to Point or typed derived from Point.

like image 186
juanchopanza Avatar answered Dec 19 '25 13:12

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!