I have a vector and want to store int data in to it at run time can I store the data in a 2D vector in this manner ?
std::vector> n
Here is one more approach.
#include
#include
#include
#include
int main()
{
std::vector > normal;
normal.resize( 10, std::vector( 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
#include
#include
#include
template
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> v;
for ( const auto &v : init_2d( v, 10, 20 ) )
{
for ( int x : v ) std::cout << std::setw( 2 ) << x << ' ';
std::cout << std::endl;
}
}