C++ equivalent of Maps / ArrayLists in java?

Started by
3 comments, last by Timberl 19 years, 6 months ago
I know in C++ you have 'vector' and 'map' in the std, but they can only have one kind of value in the key-value pair. I'm really after a java equivalent Map, where you can have any type for the value of the key-value pair, at least I'd like the option of a string, double or pointer. any suggestions?
Advertisement
Perhaps you're looking for Boost.Variant? You can use the variant as the value type in your maps and vectors.
vector and map are the closest equivalents of ArrayList and Map—specifically, if you make the value_type of the C++ containers T* for some type T, that's as close as you'll get. Java containers do not accept any type—they accept Oject references, and therefore references to any type derived from Object (which in Java is, of course, nearly anything). If your objects are part of an inheritance hierarchy (which is obviously not the case for string and double), you can accomplish the same effect with a map<base*>.

While dcosborn's solution will surely work, you should perhaps think twice before employing it: Why do you need heterogenous containers? If you intend to perform uniform operations on them, you will run into trouble, and if you do not, why can you not employ several data structures?

It is interesting to note that one of the big new things in Java 1.5 is the introduction of generics, which are essentially a subset of templates for the purpose of making typesafe containers.
It really depends on what you plan on doing to the data in the vector or map. If you're going to be doing pretty much anything besides reading stuff in or printing stuff out, then you should seriously consider reworking your program into a separate data structure for each type you'll be storing. If all you're doing is reading stuff in or printing stuff out, then a relatively simple solution is

struct MyData{// Empty struct}; struct MyData_string : public MyData{	string data;}; struct MyData_double : public MyData{	double data;};// Etc. vector<MyData *> vectorOfDifferentStuff;vectorOfDifferentStuff.push_back(new MyData_string("Hello, world!"));vectorOfDifferentStuff.push_back(new MyData_double(3.14159));...for(vector<MyData *>::iterator i = vectorOfDifferentStuff.begin(); i != vectorOfDifferentStuff.end(); i++)	delete vectorOfDifferentStuff; // Very important!  Memory leaks are bad!vectorOfDifferentStuff.clear();
thanx 4 the responses.

yep, I think separate data structures may be the best solution. though I liked the boost.variant idea, I could do without another library and overhead.

I was thinking that the key-order was important to maintain, which would be an irritation if I had 3 lists, but actually I can probably work around it.

This topic is closed to new replies.

Advertisement