Reputation: 5175
I need a vector that can store int's or float's or string's or char's or any other primitive data type inside itself.
How can I declare such a datatype ?
For example, if I use std::vector<int> vIntVector;
vIntVector is only capable of storing integers, not std::string's or floats.
P.S. I do not have C++11 support
Upvotes: 1
Views: 636
Reputation: 1435
Well, as I understood, u just want an array to store variable of different types. Unfortunately there is no simple way to do it in C++. I can suggest you the following solution.
struct Var{
enum {INT, FLOAT, BYTE} type;
union{
int integer;
float decimal;
unsigned char byte;
};
Var(int v):type(INT), integer(v){}
Var(float v):type(FLOAT), decimal(v){}
Var(unsigned char v):type(BYTE), byte(v){}
};
...
std::vector<Var> arr;
arr.push_back(1); // Push integer
arr.push_back(12.f); // Push float
arr.push_back('a'); // Push char(byte)
But I'd recommend you to not use this. Try to think about other way to implement what you need.
Upvotes: 1
Reputation: 361692
You could use Boost.Variant
if you know the possible types already. Else use Boost.Any
.
If you cannot use Boost, may be because it is too huge, then still use it!
If you still don't want to use it, see their implementation, learn from them and then define your own classes.
Upvotes: 10