Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;:对向量排序<;结构>;(其中struct有2个整数)基于struct的一个整数 在下面的C++片段中,_C++_Sorting_C++11_Visual C++_Vector - Fatal编程技术网

C++;:对向量排序<;结构>;(其中struct有2个整数)基于struct的一个整数 在下面的C++片段中,

C++;:对向量排序<;结构>;(其中struct有2个整数)基于struct的一个整数 在下面的C++片段中,,c++,sorting,c++11,visual-c++,vector,C++,Sorting,C++11,Visual C++,Vector,如何根据TwoInts结构中的元素“int a”对向量“TwoIntsVec”进行排序。i、 e.我需要将“TwoIntsVec[i].a”最少的“TwoIntsVec[i].a”放在第一位,依此类推,按“TwoIntsVec[i].a”的递增顺序排列 在下面的示例中,具有7,3的向量元素结构应该放在第一位,因为7是最小的“a”,依此类推 struct TwoInts { int a; int b; }; void PushToVector(int a, int b, std:

如何根据TwoInts结构中的元素“int a”对向量“TwoIntsVec”进行排序。i、 e.我需要将“TwoIntsVec[i].a”最少的“TwoIntsVec[i].a”放在第一位,依此类推,按“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



}
struct TwoInts
{
INTA;
int b;
};
void PushToVector(inta、intb、std::vector和TwoIntsVec)
{
两点温度;
温度a=a;
温度b=b;
TwoIntsVec.推回(温度);
}
int main()
{
std::向量TwoIntsVec;
PushToVector(21,3,TwoIntsVec);
PushToVector(7,3,TwoIntsVec);
PushToVector(12,3,TwoIntsVec);
PushToVector(9,3,TwoIntsVec);
PushToVector(16,3,TwoIntsVec);
//下面的排序在这里不起作用,就像TwoIntsVec一样
//不是std::vector
排序(TwoIntsVec.begin(),TwoIntsVec.end());
//如何基于中的元素“int a”进行排序
TwoInts结构
}

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

comp-返回的比较函数对象(即满足比较要求的对象)​
true
如果第一个参数小于第二个参数(即排序早于第二个参数)。[…]

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

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

要么实现一个
操作符哦,太棒了。我得仔细看看这些骗局。
#include <boost/hof/proj.hpp>
#include <boost/hof/placeholders.hpp>

using namespace boost::hof;

std::sort(TwoIntsVec.begin(), TwoIntsVec.end(), proj(&TwoInts::a, _ < _));
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});

// ...