Interpreting elements in the parentheses following a vector declaration

Hi, I have come across the following code while trying to understand a program:

 
    vector<double> P(ny*ny, 0.0);


Based on what I have read in a tutorial, the first component in the parentheses should be the first element in the vector, and the second component should be the last element in the vector. In this case the second component is 0.0, which is strange to me, because previously ny was assigned a value of 21. Please help. Thank you very much.
I am afraid you misunderstood or the tutorial is rubbish. The first element in the parentheses is the number of elemenst and second is the value for all elements.

See under fill (2) http://www.cplusplus.com/reference/vector/vector/vector/
Thanks for the swift response! That solves my problem.
OP: are you sure the parentheses were rounded and not curly?
http://en.cppreference.com/w/cpp/language/aggregate_initialization
1
2
3
4
5
6
7
8
9
# include <iostream>
# include <vector>

constexpr auto ny = 5;
int main()
{
    std::vector<double> P{ny*ny, 0.0};
    for (const auto& elem : P)std::cout << elem << " ";
}

In this case the second component is 0.0, which is strange to me, because previously ny was assigned a value of 21.

in either case above statement makes no sense

OP: are you sure the parentheses were rounded and not curly?

Using the constructor (parentheses) creates a vector with ny * ny (25) elements with all the elements initialized to zero. Using aggregate_initialization {} produces a vector with two elements with values of 25.0 and 0.0.

Last edited on
Using aggregate_initialization {} produces a vector with two elements with values of 25.0 and 0.0

indeed, that's what the program following demonstrates
Which is not the same as the code in OP, which creates a vector of size 25 with all elements initialized to zero.
hence the question to clarify:
OP: are you sure the parentheses were rounded and not curly?
read the posts carefully
I did read the post carefully, perhaps you need to take your own advice?

I did read the post carefully,

evidently not
Last edited on
OP: are you sure the parentheses were rounded and not curly?


Yes, the parenthese were rounded. We'll see...if the program doesn't run I'll have to come back here lol
Using the constructor (parentheses) creates a vector with ny * ny (25) elements with all the elements initialized to zero. Using aggregate_initialization {} produces a vector with two elements with values of 25.0 and 0.0.


Thanks for the information. It's amazing how people who came up with these languages were able to put in so many detailed rules.
Topic archived. No new replies allowed.