If you need to store elements of different types, you should look into polymorphism and class hierarchies. For example, if you had two different classes A and B, and needed a vector to hold either of those, you could make sure that they share a common base class.
You could then store pointers or references to such objects in one and the same vector, like so (using smart pointers in this case):
#include <iostream>
#include <memory>
#include <vector>
class Base {
public:
virtual ~Base() {}
virtual void print() = 0;
};
using BasePtr = std::shared_ptr<Base>;
class A : public Base {
public:
virtual void print() override { std::cout << "I'm an A" << std::endl; }
};
class B : public Base {
public:
virtual void print() override { std::cout << "I'm a B" << std::endl; }
};
void print(const std::vector<BasePtr>& v) {
for (auto&& i : v)
i->print();
}
int main()
{
std::vector<BasePtr> v;
v.push_back(std::make_shared<A>()); /* create and add an element of type A */
v.push_back(std::make_shared<B>()); /* create and add an element of type B */
print(v);
}
(Also, note that I'm passing the vector
type as const reference, otherwise it would be copied before being passed into the function.)