I often need to create a 2D array with width and height (let them be n and m) unknown at compile time, usually I write :
vector arr(n * m);
A std::vector
of std::vector
's (from #include
) would do the same thing as a 2-Dimensional array:
int n = 10, m = 10; //vector dimensions
std::vector> arr(n, std::vector(m)); //Create 2D vector (vector will be stored as "std::vector arr(n * m);
//you can get values from 2D vector the same way that you can for arrays
int a = 5, b = 5, value = 12345;
arr[a][b] = 12345;
std::cout << "The element at position (" << a << ", " << b << ") is " << arr[a][b] << "." << std::endl;
outputs:
The element at position (5, 5) is 12345.