C++/Size of a 2d vector

别说谁变了你拦得住时间么 提交于 2019-12-03 04:52:18
Shamim Hafiz

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.

You had some errors in your code, which I've fixed and commented on below.

vector < vector <int> > v2d;

for (int x = 0; x < 3; x++)
{
    // Move push_back() into the outer loop so it's called once per
    // iteration of the x-loop
    v2d.push_back(vector <int> ());
    for (int y = 0; y < 5; y++)
    {
        v2d[x].push_back(y);
    }
}

cout<<v2d.size()<<endl; // Remove the [0]
cout<<v2d[0].size()<<endl; // Remove one [0]

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 with v2d.size() * v2d[0].size(). Otherwise you need to loop through the "rows":

int size = 0;
for (int i = 0; i < v2d.size(); i++)
    size += v2d[i].size();

As a change, you can also use iterators:

int size = 0;
for (vector<vector<int> >::const_iterator it = v2d.begin(); it != v2d.end(); ++it)
    size += it->size();

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.

int size = 0;
for(int i = 0; i < v2d.size(); i++)
    size += v2d[i].size();
int size_row = v2d.size();
int size_col = v2d[0].size();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!