Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find largest value of a tuple element c++

I was wondering if there is a succinct way of finding the max value of one of the elements in a vector of tuples. e.g. for the following, say I want to find the largest second value of the tuple in the vector of tuples.

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

The result should be 6.

One way I could do this would be 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 though, that because you are essentially iterating over things twice, this could be done much more simply?

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

like image 343
ALs Avatar asked Dec 01 '22 15:12

ALs


2 Answers

In one pass, with custom comparer:

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));
like image 135
Jarod42 Avatar answered Dec 04 '22 14:12

Jarod42


Use max_element with a custom predicate:

auto maxVal = get<1>(*max_element(foo.begin(), foo.end(), 
                      [](auto& l, auto& r) {return get<1>(l) < get<1>(r);}));   
like image 29
DAle Avatar answered Dec 04 '22 13:12

DAle