pan*_*ami 19 c++ size vector dimensions
如何找到二维向量的大小?到目前为止,我有以下代码,无法编译.
#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;
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*fiz 27
要获得v2d的大小,只需使用v2d.size().对于v2d中每个向量的大小,请使用v2d [k] .size().
注:为获得全尺寸的v2d,总结每个个体向量的大小,因为每个矢量都有自己的大小.
mar*_*cog 10
你的代码中有一些错误,我已在下面修复并评论过.
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]
Run Code Online (Sandbox Code Playgroud)
v2d.size()返回2D矢量中的矢量数.v2d[x].size()返回"row"中的向量数x.如果您知道矢量是矩形的(所有"行"具有相同的大小),您可以获得总大小v2d.size() * v2d[0].size().否则你需要遍历"行":
int size = 0;
for (int i = 0; i < v2d.size(); i++)
size += v2d[i].size();
Run Code Online (Sandbox Code Playgroud)
作为更改,您还可以使用迭代器:
int size = 0;
for (vector<vector<int> >::const_iterator it = v2d.begin(); it != v2d.end(); ++it)
size += it->size();
Run Code Online (Sandbox Code Playgroud)
在vector<vector<int>>没有一个全尺寸的,因为在它的每个向量具有独立的尺寸.您需要将所有包含的向量的大小相加.
int size = 0;
for(int i = 0; i < v2d.size(); i++)
size += v2d[i].size();
Run Code Online (Sandbox Code Playgroud)