2D Vector in C++ with User Defined Size



In C++, a vector is a dynamic array used to store elements. A 2D vector is a vector of vectors, which is useful for things like matrices or grids. In this tutorial, we'll show you how to create and use 2D vectors with a size you choose.

A 2D vector is like a grid, where each row is a vector inside the main vector. The outer vector holds rows, and each row is a vector containing columns.

For example, a 3x3 grid would look like this:

Row 1: [1, 2, 3]  
Row 2: [4, 5, 6]  
Row 3: [7, 8, 9]

In this case, each row is a vector, and the entire grid is a vector of rows. You can easily change the number of rows and columns to fit your needs.

To help you understand how to work with 2D vectors clearly, we will cover the following topics:

Declaring a 2D Vector

To declare a 2D vector, you can use the following syntax:

std::vector<std::vector<int>> matrix;

This creates an empty 2D vector. However, if you want to initialize it with a specific number of rows and columns, you'll use the constructor like this:

std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));

Here, rows defines the number of rows in the 2D vector, and std::vector<int>(cols) creates each row with cols elements.

Example

Here's a complete example of declaring and using a 2D vector in C++. We initialize a 2D vector matrix with 3 rows and 4 columns. The matrix is filled with numbers starting from 1, and the code then prints the matrix in a 3x4 grid.

#include <iostream>
#include <vector>

int main() {
    int rows = 3, cols = 4;
    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));

    // Fill the matrix with values
    int value = 1;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            matrix[i][j] = value++;
        }
    }

    // Display the matrix
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

Below is the output of the program, which displays the 3x4 matrix filled with numbers from 1 to 12:

1 2 3 4 
5 6 7 8 
9 10 11 12

Taking User Input for 2D Vector Size

In many cases, we may want to let the user decide the size of the 2D vector. To do this, we ask for the number of rows and columns, and then resize the vector based on the user's input. Here's what we do in this process:

  • We first ask the user to enter the number of rows and columns for the 2D vector.
  • Then, we initialize the 2D vector using std::vector<std::vector<int>> with the specified number of rows and columns.
  • Next, we use nested loops to prompt the user to fill in each value in the matrix.
  • Once the matrix is filled, we print it out row by row.

Example

Here's a complete example where we take user input to create and populate a 2D vector:

#include <iostream>
#include <vector>

int main() {
    int rows, cols;
    
    // Ask the user to input the number of rows and columns
    std::cout << "Enter the number of rows: ";
    std::cin >> rows;
    std::cout << "Enter the number of columns: ";
    std::cin >> cols;
    
    // Initialize the 2D vector based on user input
    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));
    
    // Populate the matrix with values from the user
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << "Enter value for position [" << i << "][" << j << "]: ";
            std::cin >> matrix[i][j];
        }
    }

    // Display the matrix
    std::cout << "The 2D Matrix is:" << std::endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

Here's an example of what the output would look like:

Enter the number of rows: 2
Enter the number of columns: 3
Enter value for position [0][0]: 1
Enter value for position [0][1]: 2
Enter value for position [0][2]: 3
Enter value for position [1][0]: 4
Enter value for position [1][1]: 5
Enter value for position [1][2]: 6
The 2D Matrix is:
1 2 3 
4 5 6

Accessing and Modifying Elements in a 2D Vector

In a 2D vector, elements are organized in rows and columns. To work with these elements, you need to access or modify them using their specific row and column indices. This allows you to get or change the value of any element in the matrix.

Accessing Elements

To access an element in a 2D vector, you use two indices: one for the row and one for the column.

int value = matrix[i][j];  // Access the element at row i, column j

In this example, matrix[i][j] retrieves the value at the i-th row and j-th column of the matrix.

Modifying Elements

To modify an element in a 2D vector, you use the same two indices and assign a new value.

matrix[i][j] = new_value;  // Modify the element at row i, column j

In this case, matrix[i][j] is updated with new_value at the specified position in the matrix.

Displaying the 2D Vector

To display a 2D vector, you need to iterate through both the rows and the columns. This can be done using nested for loops.

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        std::cout << matrix[i][j] << " ";
    }
    std::cout << std::endl;
}

This will print the matrix row by row, with elements separated by spaces.

Handling Edge Case

When working with 2D vectors, it's important to handle possible edge cases that could cause errors or unexpected behavior. Here are a few common edge cases to watch out for:

Invalid Input for Rows or Columns

To avoid creating an empty matrix, ensure that the number of rows and columns is greater than 0. If the user enters invalid input (e.g., a negative or zero value), you should display an error message and exit the program.

if (rows <= 0 || cols <= 0) {
    std::cout << "Invalid input! Rows and columns must be positive numbers." << std::endl;
    return -1;  // Exit the program if the input is invalid
}

Empty Matrix

If either the number of rows or columns is zero, you may want to handle it appropriately by displaying a message or me action to her operations on the empty matrix.

Conclusion

In this article, we learned that 2D vectors in C++ are a simple and flexible way to handle grid-like data. By understanding how to create, set up, and work with them, you can easily manage tasks like matrices or tables, making 2D vectors a helpful tool in many programming problems.

Updated on: 2025-02-14T18:08:22+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements