C :对矢量进行排序< struct>(结构有2个整数)基于结构的整数之一

C++: Sort a vector<struct> (where struct has 2 integers) based on the one of the integers of struct

本文关键字:整数 结构 2个 于结构 gt struct lt 排序      更新时间:2023-10-16

在以下C 片段中,

如何基于twiNints struct 中的元素" int a"对向量" twiNtsvec"进行排序。即,我需要放置" TwiNtsvec [i],它的" TwiNtsvec [i] .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

}

您需要将适当的比较功能传递给std::sort,因为TwoInts没有适当的比较操作员。请参阅此处的Overload#3,其中包含此比较参数的描述:

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

一个C 11选项是通过lambda:

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

如果您发现这需要太多打字,则可以使用这样的增压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});
// ...