initialize 2d vector of ints c++

To initialize a 2D vector of ints in C++, you can follow these steps:

  1. Declare the 2D vector: Start by declaring a variable of type vector<vector<int>> to represent the 2D vector. You can choose a suitable name for the variable.

  2. Set the size of the vector: Determine the desired size of the 2D vector by specifying the number of rows and columns. You can use the resize() function to set the size of the vector accordingly. For example, if you want a 2D vector with 3 rows and 4 columns, you can use vectorName.resize(3, vector<int>(4)).

  3. Initialize the elements: Once the size of the vector is set, you can initialize the elements with the desired values. You can access individual elements using the row and column indices, and assign values to them using the assignment operator (=). For example, to assign the value 10 to the element at row 1, column 2, you can use vectorName[1][2] = 10.

Here is an example code snippet that demonstrates the initialization of a 2D vector of ints:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<vector<int>> matrix;
    matrix.resize(3, vector<int>(4));

    // Initializing elements
    matrix[0][0] = 1;
    matrix[0][1] = 2;
    matrix[0][2] = 3;
    matrix[0][3] = 4;
    matrix[1][0] = 5;
    matrix[1][1] = 6;
    matrix[1][2] = 7;
    matrix[1][3] = 8;
    matrix[2][0] = 9;
    matrix[2][1] = 10;
    matrix[2][2] = 11;
    matrix[2][3] = 12;

    // Printing the matrix
    for (int i = 0; i < matrix.size(); ++i) {
        for (int j = 0; j < matrix[i].size(); ++j) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

This code declares a 2D vector named 'matrix' with 3 rows and 4 columns. It initializes the elements with values from 1 to 12. Finally, it prints the matrix to the console.