run-time created 2 dimensional vector
Mar 15, 2018 at 5:27pm UTC
Both Visual C++ 2017 and TDM-GCC 4.9.2 initialize the elements of a created 2D vector without having to push back any values. The vector elements seem to be initialized to zero upon creation. 32-bit and 64 bit compilation results in the same behavior.
Is this correct behavior? Am I missing some key idea and fooled that two compilers seem to work without undefined behavior?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include <iostream>
#include <vector>
int main()
{
std::cout << "Creating a 2-dimensional vector, enter row size: " ;
int row_size;
std::cin >> row_size;
std::cout << "Enter column size: " ;
int col_size;
std::cin >> col_size;
std::cout << '\n' ;
// create a 2 dimensional vector
std::vector<std::vector<int >> aVector(row_size, std::vector<int >(col_size));
// let's display the newly created 2D vector before setting values
for (int row_loop = 0; row_loop < row_size; row_loop++)
{
for (int col_loop = 0; col_loop < col_size; col_loop++)
{
// let's display the newly created 2D vector
std::cout << aVector[row_loop][col_loop] << ' ' ;
}
std::cout << '\n' ;
}
std::cout << '\n' ;
// initialize the vector with some values
for (int row_loop = 0; row_loop < row_size; row_loop++)
{
for (int col_loop = 0; col_loop < col_size; col_loop++)
{
aVector[row_loop][col_loop] = ((row_loop + 1) * 100 + col_loop + 1);
}
}
// let's display the filled 2D vector
for (int row_loop = 0; row_loop < row_size; row_loop++)
{
for (int col_loop = 0; col_loop < col_size; col_loop++)
{
// let's display the filled 2D vector
std::cout << aVector[row_loop][col_loop] << ' ' ;
}
std::cout << '\n' ;
}
std::cout << '\n' ;
}
A test run with either compiler:
Creating a 2-dimensional vector, enter row size: 5
Enter column size: 3
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
101 102 103
201 202 203
301 302 303
401 402 403
501 502 503
Last edited on Mar 15, 2018 at 5:30pm UTC
Mar 15, 2018 at 6:18pm UTC
The vector elements seem to be initialized to zero upon creation.
Actually they are "default" initialized. For numeric POD types this will yield zero.
Is this correct behavior?
Yes.
Mar 15, 2018 at 6:38pm UTC
Ah, I see why now.
Because I supplied vector count size for each dimension.
Thank you, jlb, I was really confused.
Topic archived. No new replies allowed.