-
Either Or
Hey every1,
Just wonderin,
I want to have a map datastructure where the second element is always an int but the first can be an int, or a string. Is this possible in C++.
So, something like
Code:
std::map <int | std::string, int> my_map
Is that a possibility? I want to build up a map (or something similar) where each element is the key to some number. The elements will be of two types, either strings or numbers. I won't know beforehand what the percentage of each will be.
Any help wud be well appreciated.
Cheers,
Rob.
-
Use a union (or some STL container which acts as a union)?
Code:
struct foo {
enum { isInt, isString } type;
union {
int a;
std::string b;
};
};
std::map < foo, int> my_map
-
I would think it would be easier and better to use two maps, one for the ints and one for the strings.
Unless the order of your elements is important and sometimes strings come before ints and sometimes after. In that case you'd need a specialized operator< for your struct that holds the union so that it could determine the appropriate order. Another solution would be to have a Key class, then derive a StringKey and an IntKey. Again, you'd have to have a special method that determines which one is less given two generic keys, and you'd have to worry about object lifetime because you wouldn't be able to store the base object directly in the map.
However, I still think two maps is usually the way to go, because usually you have no reason to sort the keys with ints mixed in with the strings.