我想知道是否有一种简洁的方法可以找到元组 vector 中其中一个元素的最大值。例如对于以下内容,假设我想在元组 vector 中找到元组的第二大值。
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));
关于c++ - 查找元组元素的最大值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47287982/