Evgeni Genchev
Evgeni Genchev

Reputation: 47

STL minmax doesn't return pair properly

In the C++ documentation as far as I read std::minmax_element should return a std::pair<obj, obj> but when I try to return the result of the stl function I get an exception.

My class:

class obj {       
  public:             
    int num;        
    std::string name;  
};

My function:


std::pair<obj, obj> func (_Iter begin, _Iter end) const noexcept{
    return std::minmax_element(begin, end, [](const obj& l, const obj& r){
    return l.num < r.num;
});
}

Upvotes: 1

Views: 49

Answers (1)

Jarod42
Jarod42

Reputation: 218098

std::minmax_element returns pair of iterators.

You need:

std::pair<obj, obj> func (_Iter begin, _Iter end) const noexcept{
    auto [minIt, maxIt] = std::minmax_element(begin, end, [](const obj& l, const obj& r){
    return l.num < r.num;
});
    return {*minIt, *maxIt};
}

Ignoring empty range.

Upvotes: 1

Related Questions