How do I find the size of a 2 dimensional vector? So far I have the following code which doesn't compile.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < vector <int> > v2d;
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 5; y++)
{
v2d.push_back(vector <int> ());
v2d[x].push_back(y);
}
}
cout<<v2d[0].size()<<endl;
cout<<v2d[0][0].size()<<endl;
return 0;
}
You had some errors in your code, which I've fixed and commented on below.
v2d.size()
returns the number of vectors in the 2D vector.v2d[x].size()
returns the number of vectors in "row"x
. If you know the vector is rectangular (all "rows" are of the same size), you can get the total size withv2d.size() * v2d[0].size()
. Otherwise you need to loop through the "rows":As a change, you can also use iterators:
The
vector<vector<int>>
does not have a whole size, because each vector within it has an independent size. You need to sum the size of all contained vectors.To get the size of v2d, simply use v2d.size(). For size of each vector inside v2d, use v2d[k].size().
Note: for getting the whole size of
v2d
, sum up the size of each individual vector, as each vector has its own size.