Is this a vector of 24 vectors all initialised to '-1'? If so, then why isn't the hour vector of type 'vector' instead of 'double'?
I can't visualise the data structure this'll form.
vector<double> hour { vector<double>(24, -1) };
This will result in a single vector of 24 -1s named hour
. The vector<double>(24, -1)
inside of the {}
is a temporary vector that is created in order to create the hour
vector.
Visually, with '.0' omitted:
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}
If so, then why isn't the hour vector of type 'vector' instead of 'double'?
The hour vector is of type vector<double>
The <> are for templates and determine at compile time what type the vector will contain.
If it had said vector<int> hour
instead, this would have been a vector of int
values instead of double
values.
As per the cppreference page , this is the constructor form
vector(size_type count,
const T& value,
const Allocator& alloc = Allocator());
// Constructs the container with <count> copies of elements, each with value <value>.
with the default allocator.
Hence it constructs a vector of size 24
with each element of that vector set to -1
.
And the type of hour
is neither double
nor vector
, it's vector<double>
which is, surprisingly, a vector of doubles :-)
it is first constructing a instance of a vector of double with 24 items initialized with -1.0(implicitly), then it is copy constructed to create a new vector of double named hour.
update : modern compiler will have optimizations that uses move semantics for this operation, and will not do a deep copying.
the better way for doing this is simply vector<double> hour(24, -1);
vector<double>(24, -1)
creates a vector with with size 24
and each value initialized to -1
. vector <double> hour{vector<double>(24, -1)}
uses a copy constructor to make a copy of this vector so it ends up with 24
-1
s as well.
{-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0}
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.