Dear all,

I am trying to understand a C++ code.
In one part of the code a one dimensional vector is copied into a two dimensional vector.
I do not understand at all how such thing can work. But compiler is quite ok with that.

#define TOTAL_STEPS 120
#define NUMBER_DECISION_VARIABLES 5
int main(){

vector<vector<double> > DV;

vector<double> grid ( TOTAL_STEPS,0.0);

vector<double>temp ( NUMBER_DECISION_VARIABLES,0.0);

temp[0] = 0.0;
temp[1] = 0.65;
temp[2] = 0.2;
temp[3] = 0.6;
temp[4] = 0.3;

DV.resize( grid.size(), temp); // <<<<<<------------------ here ??


return 0;
}

DV[][] is 120*120 and temp[] is 5, How does it work?

If a vector is 120 elements, you don't have to use all 120 elements of it. You can use any number of elements you wish as long as they have indexes in the range [0, 120).

It's a waste of resources, but it's completely legal.

If a vector is 120 elements, you don't have to use all 120 elements of it. You can use any number of elements you wish as long as they have indexes in the range [0, 120).

It's a waste of resources, but it's completely legal.

Well , 120 elements will be all used later in the program!
But, after copying temp[] to DV[][] you can see elements of temp in DV, but what is the algorithm for that? How it copies?

Have a look at this.

To summarize, if a second parameter is used when vector::resize is called, the copy operation is part of the resize operation.

As a result, I suspect that the grid is actually 120x5, not 120x120 because the size of DV and its sub-vectors were not initially specified.

Dear Fbody,
You are right, DV is [120][50] .
Great help!
Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.