簡體   English   中英

C ++ / 2d向量的大小

[英]C++/Size of a 2d vector

如何找到二維向量的大小? 到目前為止,我有以下代碼,無法編譯。

#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;
}

要獲得v2d的大小,只需使用v2d.size() 對於v2d中每個向量的大小,請使用v2d [k] .size()

注意:為了獲得v2d整個大小 ,總結每個向量的大小,因為每個向量都有自己的大小。

你的代碼中有一些錯誤,我已在下面修復並評論過。

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()返回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();

作為更改,您還可以使用迭代器

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

vector<vector<int>>沒有整個大小,因為其中的每個向量都有一個獨立的大小。 您需要將所有包含的向量的大小相加。

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM