【发布时间】: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
}
【问题讨论】:
-
要么为你的结构实现
operator<函数,要么将谓词(例如 lambda expression)传递给std::sort。
标签: c++ sorting c++11 visual-c++ vector