-
October 3rd, 2009, 07:32 PM
#1
C++ Map with multiple data types?
Hi everyone!
I'm doing a C++ problem that I'm a bit stuck on.
I'd like to be able to store multiple data types in a C++ container with a key (such as a Map)...
Is there any way to do this or another way I should be approaching this?
Thanks
-
October 3rd, 2009, 08:52 PM
#2
Re: C++ Map with multiple data types?
There are a few possible approaches.
You can make the mapped type be designed to contain one of several types. A C union, for instance, or a boost::variant or boost::any in the C++ case.
Alternatively, you can map to a pointer to a base class (or smart pointer, such as a boost::shared_ptr) and then put classes derived from it into the map.
Which approach is better, or if yet another one should be sought, depends on your high-level requirements.
-
October 4th, 2009, 02:21 AM
#3
Re: C++ Map with multiple data types?
It depends on the set of data types you want to store. If they are simple, you can make union as advised by Lindley.
If data types are complex, make a base class, and derive other 'data-type' classes from it. Make an object of map like:
Code:
std::map<int, Base*>
In this case, however, you need to allocate appropriate class object before inserting to map. Also, you need to delete the class object after you remove element from map. Make the destructor virtual.
Lindley, not everyone can use boost.
-
November 9th, 2009, 12:34 PM
#4
Re: C++ Map with multiple data types?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|