V.R. Marinov wrote:
On Jun 8, 8:10 pm, desktop <f...@sss.com> wrote:
The problem seems to occur when I do an insert:
test t1;
my_set.insert(t1);
as long as I don't insert I can make a set with or without specifying
std::less<test> and without implementing the '<' in test.
When doing an insert I must implement the '<' operator in test and it
makes no difference if I specify std::less<test> or not.
OK. So std::set<> sorts the elements when they are inserted. In order
to sort them it needs
a criteria. The default criteria used by std::sort is the template
function (or functor/function object) called std::less<>. Here is how
std::less<> might look like:
template <class _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
So as you can see the std::less<test> uses the < operator.
So *you* need to provide < operator in way possible for std::less to
use it.
But I am not sure what to put in the body of '<'. Currently I have:
bool operator <(test const& t) const {
return (*this).getpp() < t.getpp();
}
but that was just to fill in the body.
The thing is that if you decide to std::greater<test> instead of
std::less<test>
you would have to provide a > operator.
Plus you might need to provide some more operators,
so I would suggest you create a separate header
file (e.g. test_op.h) and provide all operators needed.
This is how the < operator might look like
if you decide your class not have friend operators ;)
bool operator<(const test& lhs, const test& rhs)
{
return lhs.get() < rhs.get();
}
I get an error that the operator must take exactly one argument. But I