简体   繁体   中英

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 ie 3 , but i want the max element of either the columns ie 4 .

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

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);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM