1

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?

2
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by habib_parisa
0

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.

Edited by Fbody: n/a

0

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?

1

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.

Edited by Fbody: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.