M.A
M.A

Reputation: 1133

Errors when creating 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 ?

Upvotes: 3

Views: 191

Answers (5)

juanchopanza
juanchopanza

Reputation: 227390

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.

Upvotes: 5

M.A
M.A

Reputation: 1133

Managed to solve it. I need to make my get getScalarValue() const also. as it only returns the value.

It complies and runs without error.

Upvotes: 0

0x26res
0x26res

Reputation: 13892

  • Insert only takes 1 parameters (in your case)
  • Point::operator< should be a const member function and take a const Point as a parameter (possibly a const reference)
  • You don't need to specify less<Point> (in your case)

Upvotes: 4

There is no insert() in set which takes an element and bool. Just do s_p2.insert(tempp2);.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

The signature of insert is one of:

std::pair<iterator,bool> insert( const value_type& value );
(1) 
std::pair<iterator, bool> insert( value_type&& value );
(2) (since C++11)
iterator insert( iterator hint, const value_type& value );
iterator insert( const_iterator hint, const value_type& value );
(3) (until C++11) 
(since C++11)
iterator insert( const_iterator hint, value_type&& value );
(4) (since C++11)
template< class InputIt >
void insert( InputIt first, InputIt last );
(5) 
void insert( std::initializer_list<value_type> ilist );
(6) (since C++11)

Read value_type as Point. You're calling it with Point, bool. None of these match. What do you think the true parameter does?

Just call it as

s_p2.insert(tempp2);

Upvotes: 3

Related Questions