Can I create some sort of list of items of different type?

I have a list of vectors that look something like this:

1
2
3
4
vector<int> vec1;
vector<float> vec2;
vector<double> vec3;
vector<bool> vec4;


These vectors all describe one "node" in my code, that is to say vec1[1] describes a property of node 1, whereas vec4[1] describes a different property of the same node. As such, I often want to perform operations on nodes, and usually end up doing similar things to each of these arrays. A common operation might look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
//insert a node
vec1.insert(location,value);
vec2.insert(location,value);
vec3.insert(location,value);
vec4.insert(location,value);

//delete a node
vec1.erase(location);
vec2.erase(location);
vec3.erase(location);
vec4.erase(location);

// etc. etc. 


in my actual code, I have about 10 vectors and about 10 different functions that perform some sort of insert, erase, push_back, etc. function. It would be great if I could just have a vector or something that stored pointers to these vectors. If all of them were of the same type (let's say vector<int>) I would simply do this:

1
2
3
4
5
6
7
8
9
10
11
12
// somewhere at the start of my program
vector<*vector<int> > master_vector;
master_vector.push_back(&vec1);
master_vector.push_back(&vec2);
// etc.

// later on:

// delete a node
for (int i = 0; i != master_vector.size(); i++) {
    master_vector[i]->erase(location);
}


But of course I can't do this because all the vectors are of a different type, is there some way I can achieve this "heterogenous vector" functionality?

P.S. What about a compiler directive?
Last edited on
Alternately, you could have a struct with the four types of information in it:

1
2
3
4
5
6
7
struct node
{
  int val1;
  float val2;
  double val3;
  bool val4;
};


Then have a vector of those:

vector<struct node> myNodes;

Or did I miss some subtlety?

Cheers,
Jim
That would logically be a solution yes, however given the nature of the project it's not possible to restructure it like that.
There are no heterogeneous vectors. When one is needed, either vector of pointers to some common base class is used, or vector of variant types (boost::variant, tagged union, etc)

However, I agree with jim80y above: as described, it should be a vector of structs. You have what is known in C programming as "parallel arrays": the properties of node X are scattered across four unrelated containers. It's better, both from the point of OOP and from the point of runtime efficiency to hold the properties together, aggregated by the "Node" object.

If it's too late to redesign, you're stuck with multiple inserts, best you could do is wrap then in some helper functions (hopefully member functions of Node)
Topic archived. No new replies allowed.