473,383 Members | 1,885 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Get a C++ set to contain objects

Hi!

I'm a Java guy, forced to do some C++. I want to add objects to the set
container. I don't even get past the compilation step (which is a good
thing in a way). For instance, why doesn't the following code compile?

#include <iostream>
#include <set>

using namespace std;

class myClass {
public:
void hello() { cout << "hello"; }
};

int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error
}
The compiles gives as a reason the following:

bikCC -o prog4 prog4.cc
"/opt/SUNWspro/prod/include/CC/Cstd/./functional", line 166: Error: The
operation "const myClass<const myClass" is illegal.
"/opt/SUNWspro/prod/include/CC/Cstd/rw/tree.cc", line 177: Where:
While instantiating "std::less<myClass>::operator()(const myClass&,
const myClass&) const".
"/opt/SUNWspro/prod/include/CC/Cstd/rw/tree.cc", line 177: Where:
Instantiated from __rwstd::__rb_tree<myClass, myClass,
__rwstd::__ident<myClass, myClass>, std::less<myClass>,
std::allocator<myClass>>::insert(const myClass&).
"/opt/SUNWspro/prod/include/CC/Cstd/./set", line 224: Where:
Instantiated from non-template code.
1 Error(s) detected.

Sep 30 '06 #1
5 6678
ja****@gmail.com wrote:
int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error
}
std::set is ordered, then it needs a way to compare things (and also to
evaluate equality). You need a < operator for objects of your class, or an
specialization for him of the std::less template, or add to the definition
of your set a compare operation.

--
Salu2
Sep 30 '06 #2
ja****@gmail.com wrote:
Hi!

I'm a Java guy, forced to do some C++. I want to add objects to the set
container. I don't even get past the compilation step (which is a good
thing in a way). For instance, why doesn't the following code compile?

#include <iostream>
#include <set>

using namespace std;

class myClass {
public:
void hello() { cout << "hello"; }
};

int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error
}
[snip]

The std::set<container keeps its elements in order. For this to happen,
you need to supply a comparison predicate. Technically, you have the
following options:

a) Define an operator< for myClass. This can be either a member operator or
a freestanding friend. This solution conveys the message that the objects
of type myClass a naturally comparable.

b) Specialize std::less<myClass>. This indicates that the ordering you
define is less natural and more of a hack to make things like std::set and
std::map work.

c) Define a freestanding comparison function

bool some_function_name ( myClass const &, myClass const & );

and pass it as a parameter upon construction of the set. Generally, I would
not recommend this since you will have to supply additional template
parameters and it makes the code less readable. This, I would use only when
there are several sorting criteria for the same type that I need to use
independently in the code.
In any case, the comparison predicate you supply has to define a ordering,
i.e., you may not have things like a < b < c < a and you should have either
a<b or b<a or a==b. If these conditions are not met, the code is likely to
compiler but it is also likely to give unexpected results (aka bugs).
Best

Kai-Uwe Bux
Sep 30 '06 #3
ja****@gmail.com wrote:
Hi!

I'm a Java guy, forced to do some C++. I want to add objects to the set
container. I don't even get past the compilation step (which is a good
thing in a way). For instance, why doesn't the following code compile?

#include <iostream>
#include <set>

using namespace std;

class myClass {
public:
void hello() { cout << "hello"; }
};

int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error
}
Note, although the above compiles in Java, it wouldn't work because the
set (TreeMap in Java) has no way to compare two myClass objects to see
what the order should be.
The compiles gives as a reason the following:

bikCC -o prog4 prog4.cc
"/opt/SUNWspro/prod/include/CC/Cstd/./functional", line 166: Error: The
operation "const myClass<const myClass" is illegal.
"/opt/SUNWspro/prod/include/CC/Cstd/rw/tree.cc", line 177: Where:
While instantiating "std::less<myClass>::operator()(const myClass&,
const myClass&) const".
The above complains about the very thing that would cause this code to
fail in Java. No way to compare two myClass objects to determine order.

To do that in C++, you must provide a global function that returns true
of the left hand argument comes before the right hand argument.

bool compare( const myClass& lhs, const myClass& rhs ) {
// return true if lhs should come before rhs, otherwise return false.
}

If you name your compare function "operator<" then the set will just
work. If you want to name it something else, then you will need to let
set know.

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Sep 30 '06 #4

ja****@gmail.com wrote:
Hi!

I'm a Java guy, forced to do some C++. I want to add objects to the set
container. I don't even get past the compilation step (which is a good
thing in a way). For instance, why doesn't the following code compile?

#include <iostream>
#include <set>

using namespace std;

class myClass {
public:
void hello() { cout << "hello"; }
};

int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error
}
The compiles gives as a reason the following:

bikCC -o prog4 prog4.cc
"/opt/SUNWspro/prod/include/CC/Cstd/./functional", line 166: Error: The
operation "const myClass<const myClass" is illegal.
"/opt/SUNWspro/prod/include/CC/Cstd/rw/tree.cc", line 177: Where:
While instantiating "std::less<myClass>::operator()(const myClass&,
const myClass&) const".
"/opt/SUNWspro/prod/include/CC/Cstd/rw/tree.cc", line 177: Where:
Instantiated from __rwstd::__rb_tree<myClass, myClass,
__rwstd::__ident<myClass, myClass>, std::less<myClass>,
std::allocator<myClass>>::insert(const myClass&).
"/opt/SUNWspro/prod/include/CC/Cstd/./set", line 224: Where:
Instantiated from non-template code.
1 Error(s) detected.
You must overload myClass's operator <
Like this:

#include <iostream>
#include <set>
using namespace std;
class myClass {
public:
myClass():data(0){}
void hello() { cout << "hello"; }
bool operator<(const myClass& rhs) const
{
return data<rhs.data;
}
private:
int data;//This is a comparative data.
};
int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error

}

Sep 30 '06 #5
"Daniel T." <da******@earthlink.netwrote in message
news:da****************************@news.west.eart hlink.net...
ja****@gmail.com wrote:
>Hi!

I'm a Java guy, forced to do some C++. I want to add objects to the set
container. I don't even get past the compilation step (which is a good
thing in a way). For instance, why doesn't the following code compile?

#include <iostream>
#include <set>

using namespace std;

class myClass {
public:
void hello() { cout << "hello"; }
};

int main() {
myClass mc;

set<myClasss;
s.insert(mc); // If this line is commented away, no error
}

Note, although the above compiles in Java, it wouldn't work because the
set (TreeMap in Java) has no way to compare two myClass objects to see
what the order should be.
TreeSet surely?

<snip>
Oct 1 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: lawrence | last post by:
How dangerous or stupid is it for an object to have a reference to the object which contains it? If I have a class called $controllerForAll which has an arrray of all the objects that exist, what...
8
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was...
2
by: Daniel Goldman | last post by:
Hi, Any advice about both a BinaryReader and BinaryWriter containing same FileStream at same time? Like: Stream fs = new FileStream("output.dbf", FileMode.Create); BinaryReader br = new...
1
by: Brian | last post by:
Was browsing around online for code to connect to a database usign ADO and C#... and i found this very simple but useful reference (http://www.c-sharpcorner.com/database/db_list.asp) However,...
0
by: Stephen Horne | last post by:
I've only very recently started with .NET, and need to use some existing container libraries in new code. I'd like to minimise the amount of porting, but of course these containers are not designed...
13
by: **Developer** | last post by:
I need to sort the columns of a ListView. Some columns contain dates and others contain integers. What I did once before is in the Compare method I tried date and if that failed I did...
14
by: WENDUM Denis 47.76.11 (agent) | last post by:
While testing recursive algoritms dealing with generic lists I stumbled on infinite loops which were triggered by the fact that (at least for my version of Pyton) characters contain themselves.See...
6
by: Hubert Fritz | last post by:
Hello, I fear I want to have something which is not possible in C++. How is it possible to define a base class so that the derived class is forced to contain a static member variable, which...
2
by: alastair g | last post by:
I have a generic base class and need a list to contain different types of objects that derive from this. Public class genericBase<Twhere T: ConfigBase{} I have tried :...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.