2D vector in C++ with user defined size



In this article, we will see how we create and use 2D vectors with user-defined sizes.

What is 2D Vector?

In C++, a vector is a dynamic array used to store elements. The 2D vector is a vector of vectors and are used to create a dynamic two-dimensional array where the number of rows and the number of columns in each row can vary. Just like a 2D array, a 2D vector is used to store data in a tabular form such as matrices, grids, or tables.

Structure of a 2D Vector

A 2D vector is declared as:

vector<vector<datatype>> v;

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

To 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:
vector<vector<int>> vector_name;

2D Vector With User-defined Size

The above syntax creates an empty 2D vector. However, if you want to initialize it with a specific number of rows and columns, use the constructor below:

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

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

Constructing a 3X4 Matrix

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>
using namespace std;
int main() {
   int rows = 3, cols = 4;
   vector<vector<int>> matrix(rows, 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) {
         cout << matrix[i][j] << " ";
      }
      cout << 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

User-defined Size for a 2D Vector

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. Following are the steps:
  • We first ask the user to enter the number of rows and columns for the 2D vector.
  • Then, we initialize the 2D vector using vector<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 to Create 2D Vector with User-Defined Size

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

#include <iostream>
#include <vector>
using namespace std;
int main() {
   int rows, cols;
   cout << "Enter the number of rows: ";
   cin >> rows;
   cout << "Enter the number of columns: ";
   cin >> cols;
   // Initialize the 2D vector based on user input
   vector<vector<int>> matrix(rows, 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++) {
          cout << "Enter value for position [" << i << "][" << j << "]: ";
          cin >> matrix[i][j];
      }
   }
   // Display the matrix
   cout << "The 2D Matrix is:" << endl;
   for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
          cout << matrix[i][j] << " ";
      }
      cout << endl;
   }
   return 0;
}

Following is the output of the above code:

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, we need to access or modify them using their specific row and column indices. This allows us 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.

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

The above syntax, 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, we use the same two indices and assign a new value.

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

The above syntax, 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++) {
      cout << matrix[i][j] << " ";
   }
   cout << endl;
}

The above code display 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 behaviour. Here are a few common edge cases to watch out for:

Invalid Input for Rows or Columns

To avoid creating an empty matrix, make sure that 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) {
   cout << "Invalid input! Rows and columns must be positive numbers." <<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

2D vector is (multi-dimensional) data structure used to store grid-like data. Unlike a 2D array, we can define the size of a vector dynamically.

We have seen examples to create and declare 2D vectors with both predefined and user-defined sizes.

Updated on: 2025-07-24T15:33:39+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements