std::set

A

Austin

Here is my program:

class Test {
private:
int _num;
};

int main()
{
set<Test> aSet;
Test aTest;
aSet.insert(aTest);
return 0;
}

when compiling, vs2003 complain about operator <. If I create a class which
will be used in set, I have to implement or overload operator <? Thanks in
advance.
 
T

Tor Einar =?UTF-8?B?VMO4bm5lc3Nlbg==?=

Austin said:
Here is my program:

class Test {
private:
int _num;
};

int main()
{
set<Test> aSet;
Test aTest;
aSet.insert(aTest);
return 0;
}

when compiling, vs2003 complain about operator <. If I create a class
which
will be used in set, I have to implement or overload operator <? Thanks
in advance.

Why use Set in the first place ?
 
?

=?ISO-8859-1?Q?Erik_Wikstr=F6m?=

Here is my program:

class Test {
private:
int _num;

Try not to use names which start with _, in certain scopes they are
reserved.
};

int main()
{
set<Test> aSet;
Test aTest;
aSet.insert(aTest);
return 0;
}

when compiling, vs2003 complain about operator <. If I create a class which
will be used in set, I have to implement or overload operator <? Thanks in
advance.

No you can specify another comparator to use instead, something like
this (untested):

class Test {
int num_

friend bool cmp(const Test&, const Test&);
};


bool cmp(const Test& a, const Test& b)
return a.num_ < b.num_
}

int main()
{
std::set<Test, cmp> s;
}

But it's usually much easier to just implement operator<.
 
O

osmium

Austin said:
Here is my program:

class Test {
private:
int _num;
};

int main()
{
set<Test> aSet;
Test aTest;
aSet.insert(aTest);
return 0;
}

when compiling, vs2003 complain about operator <. If I create a class
which
will be used in set, I have to implement or overload operator <? Thanks
in
advance.

If the set consists of fundamental types, such as int, I would expect there
would be no glitch. But you have hidden your int in a class and the
compiler has no knowledge about the innards of that class. Except for the
fear factor, it should not be a big deal. Something like (untested)

bool operator<(const Test arg) {if(_num < arg._num) return
_num<arg._num;}
 
R

Ron Natalie

Austin said:
when compiling, vs2003 complain about operator <. If I create a class which
will be used in set, I have to implement or overload operator <? Thanks in
advance.
Yes, set needs a "less" relation to work. This means you must either
implement operator< or you must provide a function object to the set
to accomplish that (this by default is std::less which uses the objects
operator<).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,297
Messages
2,571,530
Members
48,252
Latest member
shilpadhussa

Latest Threads

Top