Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column size and row size of a 2D vector in C++

Tags:

c++

vector

I have a vector like this :

vector< vector<int> > myVector; 

All row and column numbers are same in this vector.

I want to find row count and column count of this vector.

For row count I come up with :

myVector[0].size(); 

For column count, I can't come up with anything. Can you tell me if my row count is correct and can you tell me how I can get column count? Thanks.

like image 298
jason Avatar asked Dec 07 '14 06:12

jason


People also ask

How do you find the size of rows and columns in a 2d vector?

vector_name. size() gives you the numbers of column in a 2D vector and vector_name[0]. size() gives you the numbers of rows in a 2D vector in C++.

What is a 2d vector?

Vectors are geometric objects. A particular vector can be represented in a variety of ways. It is important to understand the difference between a geometric object (such as a point or a vector) and the way it is represented (often with a column matrix).


Video Answer


2 Answers

You have a vector of integer vectors myVector[0].size() returns you the amount of elements in the first int vector in the 2d vector.

The structure of such vector looks like this:

myVector[   Vector[0, 4, 2, 5],   Vector[1, 4, 2] ]; 

When you call for myVector[1].size() it would return 3 and [0] would return 4.

For the amount of rows (int vectors) in the 2d vector, you can just use myVector.size()

You can run this to see it in actions

#include <iostream> #include <vector>  int main(){     std::vector<std::vector<int>>MyVector;     std::vector<int>temp;      temp.push_back(1);     temp.push_back(2);     temp.push_back(3);     MyVector.push_back(temp);      std::cout << "Rows in the 2d vector: " << MyVector.size() <<     std::endl << "Collumns in the 1st row: " << MyVector[0].size() <<     std::endl;      system("pause");     return 0; } 

This is the output:

Rows in the 2d vector: 1 Collumns in the 1st row: 3 
like image 173
Kilppari Avatar answered Sep 23 '22 11:09

Kilppari


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

Here v is a two dimensional vector of varying size in terms of column size. Use v.size() as it gives the total number of rows and v[i].size() gives you the total number of colums in ith row. The following code can be used to iterate through varying two dimensional vector.

like image 41
Manjunath Jakaraddi Avatar answered Sep 25 '22 11:09

Manjunath Jakaraddi