【问题标题】:How do I organize a vector based on two factors: id and quantity? (C++)如何根据两个因素组织向量:id 和数量? (C++)
【发布时间】:2020-06-21 18:38:17
【问题描述】:

所以,我想做的是: 我有一个结构向量。 这是结构:

struct item {
int id;
int quantity;}

我将拥有它们的向量。我不知道如何让它按 id 组织,除非两个项目具有相同的 id:在这种情况下,无论哪个项目的数量较大,都会先出现。你认为它在同类中的位置的 id 会起作用,还是有更好的解决方案?如果还有其他需要补充的信息,请告诉我,我会马上补充。

【问题讨论】:

  • 当您必须在向量中找到具有给定id 的项目时,按id 排序非常有用。

标签: c++ sorting vector struct


【解决方案1】:

类似的东西:

std::vector<item> v;  // populated somehow
std::sort(v.begin(), v.end(), [](const item& a, const item& b) {
  return std::make_tuple(a.id, b.quantity) < std::make_tuple(b.id, a.quantity);
});

【讨论】:

  • IMO,在这种情况下最好使用std::tie,因为std::make_tuple 创建了一个无用的副本。
  • 比较混合 lhs 和 rhs 可能会扰乱一些可能更喜欢(不太通用)技巧来转换字段的人,例如std::make_tuple(a.id, -a.quantity) &lt; std::make_tuple(b.id, -b.quantity)
【解决方案2】:

您可以使用预定义的排序函数并编写自己的比较器函数并将其作为第三个参数传递。 这个比较器函数返回布尔值,它告诉排序函数我们想要的确切顺序。 您的案例的比较器功能如下:

bool cmp( item a, item b)
{
   if( a.id == b.id ) // if id is same then sort quantity wise
     return a.quantity> b.quantity;  
   else                // else keyword is not necessary here 
     return  a.id < b.id ; // this means sort the vector in ascending order of                            
                           //id
}

调用排序函数并将这个比较器函数作为第三个参数传递

vector<item> v;
sort(v.begin(), v.end(),cmp); 

这里的cmp是比较器函数名,这个比较器函数按照id升序对item进行排序,如果id相同则按照数量降序排序。 http://www.cplusplus.com/reference/algorithm/sort/ 在这里你会找到更多关于排序功能的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2021-05-09
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多