jarhead
jarhead

Reputation: 1901

Structure that contains vectors with different sizes, cpp

I wish to declare a structure, say with size n=10, that in each i site of the structure there is a vector. The vectors in the sites of the structure have different sizes.

In matlab it can be obtained using struct. how it is done in C++?

Upvotes: 0

Views: 2699

Answers (2)

Numeri
Numeri

Reputation: 1047

I think what you are looking for is an array, or a vector, of vectors.

For example:

#include <array>
#include <vector>
#include <iostream>

int main ()
{
    std::array<std::vector<int>, 10> Vectors;

    for (auto &i : Vectors)    //Loop through all 10 vectors in Vectors
    {
        for (int j=0; j<5; j++) //Push 1, 2, 3, 4, and 5 into each vector
        {
            i.push_back(j);
        }
    }
    return 0;
}

Upvotes: 3

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

struct S {
    std::array<std::vector<int>, 10> data;
};

You can also use an alias as well:

using arrayOfTenVectors = std::array<std::vector<int>, 10>;

Of course int is a placeholder. You can make either the struct or the alias a template and use some T inside of the vector.

Upvotes: 0

Related Questions