سؤال

How can I declare vector of fixed size vectors in C++?

For example:

vector of vectors with N elements.

Not this:

vector<vector<int> > v(N) //declares vector of N vectors
هل كانت مفيدة؟

المحلول

std::array is your friend here.

http://en.cppreference.com/w/cpp/container/array

For instance, to declare vector of vectors with N elements, you can

typedef std::array<int, N> N_array;

Then use

std::vector<N_array>

نصائح أخرى

You could use std::array:

std::array<int, 10>    myNumbers;

The only down side to this is you can't see how many "active" elements there are, since you don't push/emplace back. You use it like an ordinary( but safe ) array.

If you wish to have vector of fixed size, most likely you don't need one! Use std::array instead.

But still you insist to have one..

vector<vector<int> > vecOfVec(NumberOfVectors);
for ( int i = 0 ; i < NumberOfVectors; i++ )
   vecOfVec[i].resize(NumberOfElementsInVector);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top