如何获得3D std :: vectors的大小?

时间:2017-06-18 14:10:14

标签: c++ multidimensional-array vector stl size

我知道如果我有一个任意大小为M乘N的二维矢量,

然后我可以通过myVector.size()

获取行中元素的数量

我可以通过myVector [0] .size()

获取列中的元素数量N

但如果我有一个2D矢量矢量,又称矢量<矢量<矢量<双>>> myVector,大小说K乘M乘N,那么我怎样才能得到K,M和N的大小?

2 个答案:

答案 0 :(得分:0)

这适用于我,它打印15。

vector< vector< vector<int> > > vec;
for (int i = 0; i < 5; i++) {
    vector< vector<int> > row;
    for (int j = 0; j < 10; j++) {
        vector<int> high;
        for (int m = 0; m < 15; m++) {
            high.push_back(i * j * m); 
        }
        row.push_back(high);
    }
    vec.push_back(row); 
}

cout << vec[0][0].size() << endl;

答案 1 :(得分:0)

我希望这会有所帮助。

#include <iostream>
#include <vector>

using std::vector;

int main()
{
    vector<vector<int> > k{{1,2}, {1,2}, {1,2}};
    vector<vector<vector<int> > > k3;

    for(int i = 0; i < 4; ++i)
        k3.push_back(k);


    // Think of a 3D vector as an array made of K matrices N x M ...
    // This will work if the 3D vector is made out of 2D matrix of same dimensions..
    int K = k3.size(); // number of matrices
    int N = k3[0].size(); // number of rows for each matrix
    int M = k3[0][0].size(); // number of lines for each matrix

    std::cout << " k = " << K << "  n = " << N << "  m = " << M << std::endl;
    return 0;
}