Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain { } container in c++

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.
like image 324
stark Avatar asked May 23 '20 12:05

stark


2 Answers

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.

like image 115
Some programmer dude Avatar answered Oct 15 '22 08:10

Some programmer dude


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.

like image 29
songyuanyao Avatar answered Oct 15 '22 08:10

songyuanyao