Reputation: 455
I am trying to learn C++. Currently I ran into a tutorial, which mentioned how to create a constant sized vector like this: vector <int> v(10);
Now I'm wondering how to create a constant sized vector of constant sized vectors, something like: vector <vector <int> (10)> v(10);
This code doesn't work, so I wanted to ask is there a way do something like this and if there is, how?
Upvotes: 2
Views: 99
Reputation: 172924
You could
vector<vector<int>> v(10, vector<int>(10));
i.e. construct the std::vector
with 10 copies of elements with value std::vector<int>(10)
.
Note that for std::vector
the size is not constant, it might be changed when element(s) are inserted or erased, 10 is just the initial size when v
and its elements get initialized. On the other hand, the size of std::array
is constant, it's specified at compile-time and can't be changed at run-time.
Upvotes: 4
Reputation: 15501
You can't have a constant sized vector of constant sized vectors without writing your own class wrapper of some kind. Use the more appropriate std::array container for the task:
std::array<std::array<int, 10>, 10> arr;
Upvotes: 3