【问题标题】:How can I find the maximum value in a vector of tuples?如何在元组向量中找到最大值?
【发布时间】:2016-08-12 13:17:37
【问题描述】:

考虑:

vector<tuple<int, int, char>> array;
for(int i=0; i<m-1; i++)
{
   long long int p;
   cin >> p;
   get<0>(x) = p; // Updated value
   get<1>(x) = get<0>(x); // Real value
   get<2>(x) = 'v';
   array.push_back(x);
}
sort(array.begin(), array.end());
reverse(array.begin(), array.end());
// How can I get the maximum of the second field
// to to element with largest first field
// and then delete the tuple?

假设我有一个数据类型元组数组int, int, char

例如,(5,5,h);(5,2,h);(5,7,v);(3,1,h);(3,7,h);(1,1 ,v)。

它已经根据第一个值按降序排序。现在我想找到包含最大第一个值和最大第二个值的部分?所以我只需要搜索前三部分。 有没有办法在这里使用 max() 或任何其他 STL 函数?

【问题讨论】:

  • 据我所知,您并没有仅对第一个值进行排序;你对整个元组进行了排序。不是这样吗?

标签: c++ arrays stl tuples max


【解决方案1】:

std::tuple::operator &lt; 执行字典比较 (Cplusplus.com)。这意味着,在sortreverse之后,array的第0项包含tuple在所有具有最大第一个元素的元组中具有最大第二个元素的所有元组中,即是你需要的。

所以,只需返回array[0]

【讨论】:

    【解决方案2】:

    如果您不想在压缩中使用第三个元组元素,并且不想使用排序和反向功能,我认为将std::max_element 与 lambda 一起使用是不错的选择,如下所示:

    typedef tuple<int, int,char> ET;
    
    auto comparator = [](ET a, ET b)
    {
       return std::tie(get<0>(a), get<1>(a)) < std::tie(get<0>(b), get<1>(b))
    }
    

    【讨论】:

      【解决方案3】:

      由于默认operator &lt;很好,你可以直接使用

      const std::vector<std::tuple<int, int, char>> tuples = // ...
      
      auto it = std::max_element(tuples.begin(), tuples.end());
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        相关资源
        最近更新 更多