I need to create a vector of vectors (Vector of 3 vectors to be precise). Each constituent vector is of different datatype (String, double, user-defined datatype). Is this possible in C++? If not, is there any other elegant way of realizing my requirement?
Vector of Vectors is a two-dimensional vector with a variable number of rows where each row is vector. Each index of vector stores a vector which can be traversed and accessed using iterators. It is similar to an Array of Vectors but with dynamic properties.
Basically vector is a dynamic array that has the ability to resize itself automatically when an element add or removed from the vector. A vector element store in a continuous manner so we can access the element using the index.
To insert/append a vector's elements to another vector, we use vector::insert() function. Syntax: //inserting elements from other containers vector::insert(iterator position, iterator start_position, iterator end_position);
Vectors are a modern programming concept, which, unfortunately, aren't built into the standard C library. Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.
If you know there's three of them, and you know their types, why not just write a class?
class Data
{
std::vector<std::string> _strings;
std::vector<double> _doubles;
std::vector<UserDefined> _userDefined;
public:
// ...
};
This would also give some strong semantics (a vector of unrelated stuff seems weird in my opinion).
template<typename T> struct inner_vectors {
std::vector<double> double_vector;
std::vector<std::string> string_vector;
std::vector<T> user_vector;
};
std::vector<inner_vectors<some_type>> vector_of_vectors;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With