Vector of vectors or different types

I would like to make a vector of vectors of different types. Suppose I have 4 classes; Dog, Cat, Pig, Cow. I would like a vector that contains vectors of each of these, and a function to access them by two indices.

I have been toying with things like:

std::vector<
std::variant<std::vector<Dog>,
std::vector<Cat>,
std::vector<Pig>,
std::vector<Cow>>>
MyArray;

but haven't got there yet. Furthermore, I'd like to be able to construct these arrays with a variadic template construct, so I could easily make another vector of vectors of, say, Apple, Pear, Orange, Lemon, Grape, Cherry.

Any ideas?
Um, this is the whole point of inheritance.

1
2
3
4
5
6
7
class Animal { ... };  // make it abstract if you wish

class Dog: public Animal { ... };
class Cat: public Animal { ... };
...

std::vector <std::vector <Animal*> > MyArrayOfAnimals;

You could, of course, use a map as well:

1
2
3
std::map <Animal::typeID, Animal*> MyAnimals;

MyAnimals[ Dog::ID ].emplace_back( new Dog( ... ) );

And, to top it off, you can use a smart pointer in your container as well.


Another approach would be to use a tuple:
1
2
3
std::tuple <std::vector <Dog> , std::vector <Cat> , ...> MyAnimals;

std::get <1> (MyAnimals).emplace_back( new Cat( ... ) );


Now, after that, this is my advice: you are making a design mistake.
Whatever it is you are trying to accomplish, you are getting tripped up by trying to be fancy with the language. Knock it off. Rethink the problem and come up with another solution.

Hope this helps.
Can you describe the problem you're trying to solve (as opposed to the solution you've come up with). I agree with Duthomhas that you're probably making a design mistake and there's probably an easier way.
Like the others, I think you need to explain your goal, but I want to point you to boost.polycollection, which is structurally similar to what you've proposed:
https://www.boost.org/doc/libs/master/doc/html/poly_collection.html#poly_collection.introduction
Topic archived. No new replies allowed.