• 15
• 15
• 11
• 9
• 10

# C++ equivalent of Maps / ArrayLists in java?

This topic is 4919 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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?

##### Share on other sites
Perhaps you're looking for Boost.Variant? You can use the variant as the value type in your maps and vectors.

##### Share on other sites
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.

##### Share on other sites
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();

##### Share on other sites
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.