Milo
Milo

Reputation: 2171

How to std::tie to unpack results of std::minmax_element?

I have a container v of elements of type T, to which I apply std::minmax_element, like so:

auto min_max = std::minmax_element(v.begin, v.end);
auto min = min_max.first;
auto max = min_max.second;

I would like to unpack the results of std::minmax_element with std::tie, but I can't figure the type for the declaration:

*type?* first_it, last_it;
std::tie(first_it, last_it) = std::minmax_element(v.begin, v.end);

What would be the type of first_it and last_it?

Upvotes: 1

Views: 264

Answers (2)

Dan
Dan

Reputation: 67

auto [min, max] = std::minmax_element(v.begin, v.end);

Upvotes: 3

rafix07
rafix07

Reputation: 20969

std::minmax_element returns a pair of iterator as member type of passed a container, so for vector it is vector<T>::iterator:

std::vector<int> v{1,2,3,4,5,2,3};
decltype(v)::iterator first_it, last_it; // or vector<int>::iterator 
std::tie(first_it,last_it) = std::minmax_element(v.begin(), v.end());

If you change for using cbegin/cend, you have to change iterator type to const_iterator.

Upvotes: 3

Related Questions