C ++:对矢量进行排序 (其中struct有2个整数)基于struct [duplicate]的整数之一

问题描述 投票:2回答:1

这个问题在这里已有答案:

在下面的C ++代码段中,

如何根据TwoInts结构中的元素“int a”排序向量“TwoIntsVec”。即,我需要在第一个位置放置具有最少“TwoIntsVec [i] .a”的“TwoIntsVec [i],依此类推,以”TwoIntsVec [i] .a“的递增顺序。

在下面的例子中,7,3的矢量elemnt结构应该放在第1位,因为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个回答
5
投票

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

comp - 比较函数对象(即满足Compare要求的对象),如果第一个参数小于(即在之前排序)第二个参数,则返回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});

// ...
© www.soinside.com 2019 - 2024. All rights reserved.