Open In App

Find Column and Row Size of a 2D Vector in C++

Last Updated : 17 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, 2D vector is the vector in which each element is a vector in itself. The number of these vectors represent the column size, and the size of each vector represents the row size. In this article we will learn how to find the row size and column size of 2D vectors in C++.

The simplest way to find the row size and column size is by using vector size() method. The column size can be determined by using this method on the 2d vector and the row size by using it on any of the member vector. Let's take a look at the code example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<vector<int>> v = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
  
    // Get column size
    cout << "Column size: " << v.size() << endl;
  
    // Get Row size
    cout << "Row size: " << v[0].size();

    return 0;
}

Output
Column size: 3
Row size: 3

Explanation: In the above method, we have taken the 2D vector in which the size of each row (member vector) is same. But in practical scenarios, it is very much possible that size of each row is different resulting in different row size. Such vectors are called jagged vectors.

Note: Numbers of rows and row size are different. Number of rows refer to the total count of horizontal lines of elements within the 2D Vector while Row Size refers to the number of elements present in each individual row of the 2D Vector. Same with number of columns and column size.

Row and Column Size for Jagged Vectors

For a jagged 2D vector, the column size can be determined same as that of normal 2D vector, but the row size would be determined by the size of every member vector.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<vector<int>> v = {
        {1, 2, 3},
        {4, 5, 6, 7},
        {8, 9}
    };
  
    // Get column size
    cout << "Column size: " << v.size() << endl;
  
    // Row size of individual row
  	for (int i = 0; i < v.size(); i++)
      	cout << "\tRow " << i + 1 << " size: "
      	<< v[i].size() << endl;

    return 0;
}

Output
Column size: 3
	Row 1 size: 3
	Row 2 size: 4
	Row 3 size: 2

Note: If the size of the 2D vector (column size) is zero, then do not try to find the row size as the empty 2D vector does not have any member vector and trying to access it may lead to segmentation fault.


Next Article
Article Tags :
Practice Tags :

Similar Reads