Here is one more approach.
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
int main()
{
std::vector<std::vector <int> > normal;
normal.resize( 10, std::vector<int>( 20 ) );
for ( auto &v : normal ) std::iota( v.begin(), v.end(), 0 );
for ( const auto &v : normal )
{
for ( int x : v ) std::cout << std::setw( 2 ) << x << ' ';
std::cout << std::endl;
}
}
The program output is
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
You can write a corresponding function
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
template <typename T>
T & init_2d( T &container, size_t m, size_t n )
{
container.resize( m, typename T::value_type( n ) );
for ( auto &item : container ) std::iota( item.begin(), item.end(), 0 );
return container;
}
int main()
{
std::vector<std::vector<int>> v;
for ( const auto &v : init_2d( v, 10, 20 ) )
{
for ( int x : v ) std::cout << std::setw( 2 ) << x << ' ';
std::cout << std::endl;
}
}
int
. If you remember that it's easy to see what you need to do: Push back a vector for each iteration of the outer loop. – Foremost