[英]find largest value of a tuple element c++
我想知道是否有一種簡潔的方法來查找元組向量中的一個元素的最大值。 例如,對於以下內容,假設我想在元組向量中找到元組的最大第二個值。
vector<tuple<int, int>> foo = { {12,1},{12,5},{5,6} };
結果應該是6。
我可以這樣做的一種方式是:
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());
我覺得,因為你實際上是在兩次迭代,這可以更簡單地完成嗎?
我的元組技能有點受限,看起來你應該能夠直接在foo上做某種max_element ...
在一次通過中,使用自定義比較器:
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));
將max_element
與自定義謂詞一起使用:
auto maxVal = get<1>(*max_element(foo.begin(), foo.end(),
[](auto& l, auto& r) {return get<1>(l) < get<1>(r);}));
具有結構化綁定的版本:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.