Find the largest value of a C ++ tuple element

I was wondering if there is a concise way to find the maximum value of one of the elements in the tuple vector. for example, for the next, let's say I want to find the largest second tuple value in the tuple vector.

vector<tuple<int, int>> foo = { {12,1},{12,5},{5,6} };

The result should be 6.

One way I could do this is with something like:

vector<double> allFoo;
for (int i = 0; i != size(foo); i++) {
    allFoo.emplace_back(get<1>(foo[i]));
}
double maxVal = *max_element(allFoo.begin(), allFoo.end());

I feel that, because, in fact, you are repeating things twice, can this be done much easier?

My typing skills are a bit limited and it seems like you should be able to do some kind of max_element directly on foo ...

+4
source share
3 answers

In one pass with custom mapping:

std::vector<std::tuple<int, int>> foo = { {12,1},{12,5},{5,6} };

const auto less_by_second = [](const auto& lhs, const auto& rhs)
    { return std::get<1>(lhs) < std::get<1>(rhs); };
const double maxVal = std::get<1>(*std::max_element(foo.begin(), foo.end(), less_by_second));
+10
source

max_element :

auto maxVal = get<1>(*max_element(foo.begin(), foo.end(), 
                      [](auto& l, auto& r) {return get<1>(l) < get<1>(r);}));   
+7

:

std::vector<std::tuple<int, int>> tv = { {12, 1}, {13,2}, {11, 1} };

auto [max1, max2] = *max_element(begin(tv), end(tv), [](auto &lhs, auto &rhs) -> int {return std::get<1>(lhs) < std::get<1>(rhs); });

cout << max2 << endl;
0

Source: https://habr.com/ru/post/1689257/


All Articles