2d stl array

To create a 2D array using the STL (Standard Template Library) in C++, you can follow these steps:

  1. Include the necessary header file: cpp #include <array>

  2. 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, and M represents the number of rows in the array. You can replace int with any other data type of your choice.

  3. Accessing elements in the array: cpp int element = myArray[row][column]; Replace row with the desired row index and column with the desired column index to access a specific element in the array.

  4. Modifying elements in the array: cpp myArray[row][column] = newValue; Replace row with the desired row index, column with the desired column index, and newValue with the value you want to assign to that element.

  5. 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.

  6. Additional operations: The std::array class provides various member functions that you can use to perform operations on the 2D array. Some common functions include size() to get the size of the array, fill() to assign a value to all elements, and swap() 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.