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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With