Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find std::max_element on std::vector<std::pair<int, int>> in either of the axis?

How do i find the max element in this pair std::vector<std::pair<int, int>> in either of the axis.

Let this be the sample pair:

0, 1
0, 2
1, 1
1, 2
1, 4
2, 2
3, 1

I tried using std::minmax_element():

const auto p = std::minmax_element(edges.begin(), edges.end());
auto max = p.second->first;

But this generates the max element only of the first column i.e 3, but i want the max element of either the columns i.e 4.

I want the max element to be the highest element of either the columns.

like image 219
Approachable Avatar asked May 22 '19 11:05

Approachable


2 Answers

Use std::max_element with a custom compare function, something like:

auto max_pair = *std::max_element(std::begin(edges), std::end(edges), 
    [](const auto& p1, const auto& p2) {
        return std::max(p1.first, p1.second) < std::max(p2.first, p2.second);
    });
int max = std::max(max_pair.first, max_pair.second);
like image 181
Paul Evans Avatar answered Nov 07 '22 08:11

Paul Evans


You need provide predicate which will define "less" relation for your items:

const auto p = std::minmax_element(
        edges.begin(), edges.end(),
        [](const auto& a, const auto& b) {
    // provide relation less you need, example:
    return std::max(a.first, a.second) < std::max(b.first, b.second);
});

By default (in your code) less operator is used. For std::pair it works in lexicographical ordering of elements (if first elements are less returns true if they are equal checks second elements if the are less).

like image 20
Marek R Avatar answered Nov 07 '22 07:11

Marek R