Can someone explain { } container in c++
Asked Answered
K

2

5

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.
Killen answered 23/5, 2020 at 12:28 Comment(0)
L
4

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.

Laurelaureano answered 23/5, 2020 at 12:31 Comment(0)
P
6

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.

Progenitor answered 23/5, 2020 at 12:32 Comment(2)
Does C++20 Ranges enhance this kind of operation? (I'm still on C++14, so I'm way behind the latest improvements.)Mages
@Mages I haven't had the time to check out ranges yet (not even the old ranges-v3 library it's mostly based on) so I don't really know. But I would guess it would.Progenitor
L
4

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.

Laurelaureano answered 23/5, 2020 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.