stark
stark

Reputation: 63

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.

Upvotes: 5

Views: 141

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

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.

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409166

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.

Upvotes: 6

Related Questions