Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Vector of vectors

Tags:

c++

stl

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?

like image 440
Spottsworth Avatar asked May 31 '11 16:05

Spottsworth


People also ask

Can you have a vector of vectors?

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.

What is vector function C?

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.

How do you add vectors to vectors?

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);

Do C have vectors?

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.


2 Answers

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).

like image 135
Etienne de Martel Avatar answered Oct 31 '22 07:10

Etienne de Martel


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;
like image 3
Puppy Avatar answered Oct 31 '22 06:10

Puppy