【问题标题】:C++: Sort a vector<struct> (where struct has 2 integers) based on the one of the integers of struct [duplicate]C ++:根据struct的整数之一对vector<struct>(其中struct有2个整数)进行排序[重复]
【发布时间】:2019-08-12 08:29:54
【问题描述】:

在下面的C++ sn-p中,

如何对向量“TwoIntsVec”进行排序基于 TwoInts 结构中的元素“int a”。即我需要将具有最少“TwoIntsVec[i].a”的“TwoIntsVec[i]”放在第一位,依此类推,按“TwoIntsVec[i].a”的递增顺序。

在下面的示例中,具有 7,3 的向量元素结构应放在第一位,因为 7 是最小的“a”,依此类推。

struct TwoInts
{
    int a;
    int b;
};

void PushToVector(int a, int b, std::vector<TwoInts>& TwoIntsVec)
{
    TwoInts temp;
    temp.a = a;
    temp.b = b;
    TwoIntsVec.push_back(temp);
}

int main()
{
    std::vector<TwoInts> TwoIntsVec;
    PushToVector(21,3,TwoIntsVec);
    PushToVector(7,3,TwoIntsVec);
    PushToVector(12,3,TwoIntsVec);
    PushToVector(9,3,TwoIntsVec);
    PushToVector(16,3,TwoIntsVec);

    // Below sort would NOT work here, as TwoIntsVec is
    // not a std::vector<int>
    std::sort( TwoIntsVec.begin(),  TwoIntsVec.end()); 

   // HOW TO MAKE THE SORT BASED ON the element "int a" in 
   TwoInts struct



}

【问题讨论】:

标签: c++ sorting c++11 visual-c++ vector


【解决方案1】:

您需要将适当的比较函数传递给std::sort,因为没有可用于TwoInts 的适当比较运算符。请参阅重载#3 here 以及此比较参数的描述:

comp - 比较函数对象(即满足比较要求的对象),如果第一个参数小于(即排在前面)第二个参数,则返回true。 [...]

一个 C++11 选项是传递一个 lambda:

 std::sort( TwoIntsVec.begin(),  TwoIntsVec.end(),
     [](const TwoInts& lhs, const TwoInts& rhs){ return lhs.a < rhs.a;  });

如果你发现这需要太多的输入,你可以像这样用Boost HOF 构造一个谓词:

#include <boost/hof/proj.hpp>
#include <boost/hof/placeholders.hpp>

using namespace boost::hof;

std::sort(TwoIntsVec.begin(), TwoIntsVec.end(), proj(&TwoInts::a, _ < _));

或者,作为 C++20 预告片:

std::ranges::sort(TwoIntsVec, std::less<>{}, &TwoInts::a);

作为旁注,我建议您直接通过填充向量

// Less complicated than doing the same thing in a function:
TwoIntsVec.push_back({21, 3});
TwoIntsVec.push_back({7, 3});

// ...

【讨论】:

  • 哦,闪亮。我得仔细看看这些范围的恶作剧。
猜你喜欢
  • 2022-11-01
  • 2016-07-16
  • 2018-08-25
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多