c++ 2d vector assign value

You can assign values to a 2D vector in C++ using the following steps:

  1. Declare the 2D vector: cpp std::vector<std::vector<int>> vec2D;

  2. Resize the vector to the desired dimensions: cpp int rows = 3; int columns = 4; vec2D.resize(rows, std::vector<int>(columns));

  3. Access the elements of the vector using the row and column indices: cpp vec2D[row_index][column_index] = value;

Here's an example that demonstrates these steps:

#include <iostream>
#include <vector>

int main() {
  std::vector<std::vector<int>> vec2D;
  int rows = 3;
  int columns = 4;

  vec2D.resize(rows, std::vector<int>(columns));

  // Assign values to the elements of the 2D vector
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
      vec2D[i][j] = i + j;
    }
  }

  // Print the values of the 2D vector
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
      std::cout << vec2D[i][j] << " ";
    }
    std::cout << std::endl;
  }

  return 0;
}

This code declares a 2D vector vec2D with 3 rows and 4 columns. The values in the vector are then assigned using nested loops, where each element is set to the sum of its row and column indices. Finally, the values of the 2D vector are printed to the console.