Can someone explain the {} in c++. it is used with all containers. example.
I generally use it to make a container like set or vector empty.
I have confusion in using the min/ max function for multiple values with it.
vector<int> v = {1,2,3,4,5};
int a = min(v) // doesn't work.
int b = min({1,2,3,4,5}) // works and gives accurate answer.
There's an overload of std::min
that takes an std::initializer_list
. And it's this overload that is used for
int b = min({1,2,3,4,5});
To get the minimum element of a generic iterable container you need to use std::min_element
:
int a = std::min_element(begin(v), end(v));
For max values use std::max
or std::max_element
, as applicable.
Both std::min
and std::max
have an overload taking std::initializer_list
, which could be constructed from braced-init-list like {1,2,3,4,5}
.
min(v)
doesn't work because there's no overload taking std::vector
.
Since C++11 STL containers like std::vector
and std::list
could be list-initialized from braced-init-list too; when being initialized from empty one (i.e. {}
) they would be value-initialized by default constructor. For non-empty braced-init-list they would be initialized by the overloaded constructor taking std::initializer_list
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With