2d stl array
To create a 2D array using the STL (Standard Template Library) in C++, you can follow these steps:
Include the necessary header file:
cpp #include <array>
Declare the 2D array using the
std::array
template:cpp std::array<std::array<int, N>, M> myArray;
In this example,N
represents the number of columns, andM
represents the number of rows in the array. You can replaceint
with any other data type of your choice.Accessing elements in the array:
cpp int element = myArray[row][column];
Replacerow
with the desired row index andcolumn
with the desired column index to access a specific element in the array.Modifying elements in the array:
cpp myArray[row][column] = newValue;
Replacerow
with the desired row index,column
with the desired column index, andnewValue
with the value you want to assign to that element.Looping through the array:
cpp for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // Access and process each element using myArray[i][j] } }
This nested loop allows you to iterate through each element of the 2D array.Additional operations: The
std::array
class provides various member functions that you can use to perform operations on the 2D array. Some common functions includesize()
to get the size of the array,fill()
to assign a value to all elements, andswap()
to swap the contents of two arrays.
Remember to replace N
and M
with the appropriate values for the number of columns and rows in your 2D array.