简体   繁体   中英

How to get the size of each dimension in a vector<vector<array<double, 2>>> construct?

I have the following construct.

An array arr :

std::array<double, 2> val;

I put this into a vector via push_back()

std::vector<std::array<double, 2>> innerVec;
for(int i=0; i<number1; i++){
   innerVec.push_back(val);
}

And again, I put this inner vector into an outer vector:

std::vector<std::vector<std::array<double, 2>>> outerVec;
for(int i=0; i<number2; i++){
   outerVec.push_back(innerVec);
}

The question is, how can I get the size (I mean actually number1 ) of innerVec ? With

outerVec[0].size();

it returns 2*number1 , what probably is because val has 2 entries and size() returns the number of elements in the inner vector.

In a jagged vector construction like that, outerVec.size() and outerVec[0].size() do the trick:

#include <vector>
#include <array>
#include <iostream>

int main()
{
    int number1 = 3;
    int number2 = 5;
    std::array<double, 2> val;
    std::vector<std::array<double, 2>> innerVec;
    for (int i = 0; i < number1; i++) {
        innerVec.push_back(val);
    }

    std::vector<std::vector<std::array<double, 2>>> outerVec;
    for (int i = 0; i < number2; i++) {
        outerVec.push_back(innerVec);
    }

    std::cout << "number1: " << outerVec[0].size() << std::endl;
    std::cout << "number2: " << outerVec.size() << std::endl;
}

it returns 2*number1 , what probably is because val has 2 entries

No, you get the size of val using outerVec[0][0].size() .

It is evident that the dimensions of the vector are [number2][number1][2] .

Here is a demonstrative program.

#include <iostream>
#include <array>
#include <vector>

int main() 
{
    const size_t number1 = 10;
    const size_t number2 = 5;

    std::vector<std::vector<std::array<double,2>>> v =
        { number2, std::vector<std::array<double, 2 >>( number1 ) };


    std::cout << "v.size() = " << v.size() << '\n';     
    std::cout << "v[0].size() = " << v[0].size() << '\n';       
    std::cout << "v[0][0].size() = " << v[0][0].size() << '\n';     

    return 0;
}

Its output is

v.size() = 5
v[0].size() = 10
v[0][0].size() = 2

Ok,

as expected you all were right ^^

The error was stupid, I simply initiated innerVec as follows:

std::vector<array<double, 2>> innerVec(number1)

And put again number1 val-elements via push_back() to innerVec. Of course this resulted in 2*number1 val-elements. Stupid mistake...

So, I am sorry for any inconveniences and thanks to every one, who helped...

Greetings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM