在下面的 C++ 代码片段中,
如何根据 TwoInts 结构中的元素“int a”对 vector “TwoIntsVec”进行排序。即,我需要将具有最少“TwoIntsVec[i].a”的“TwoIntsVec[i]”放在第一位,依此类推,按照“TwoIntsVec[i].a”的递增顺序。
在下面的示例中,具有 7,3 的 vector 元素结构应放置在第一个,因为 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
}
最佳答案
您需要将适当的比较函数传递给 std::sort
,因为没有适当的比较运算符可用于 TwoInts
。请参阅重载 #3 here以及该比较参数的描述:
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns
true
if the first argument is less than (i.e. is ordered before) the second. [...]
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);
作为旁注,我建议您直接通过填充 vector
// Less complicated than doing the same thing in a function:
TwoIntsVec.push_back({21, 3});
TwoIntsVec.push_back({7, 3});
// ...
关于C++:根据 struct 的整数之一对 vector <struct>(其中 struct 有 2 个整数)进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55281213/