我想使用 stl 排序算法对一些数字进行排序,但我也想记住它们的初始位置。我有一个这样的数据结构:
struct Numbers {
int position;
int value;
};
我创建了一个这样的数字向量:
vector<Numbers> a;
如何使用 stl 排序算法,以便我根据值对数据结构进行排序?
您需要重载“<”运算符,如下所示:
bool Numbers::operator<(Numbers temp)
{
return value < temp.value;
}
您也可以使用仿函数:
struct comp {
bool operator()(const Numbers &lhs, const Numbers& rhs) const{
lhs.value < rhs.value;
}
};
std::sort(a.begin(),a.end(), comp());
使用 C++11,您可以使用 lambda 函数:
std::sort( a.begin() , a.end() ,
[](const Numbers& lhs , const Numbers& rhs)
{ return lhs.value < rhs.value; }
);
使用std::sort
并提供自定义比较器(模板 arg Compare
)
#include <algorithm>
#include <vector>
//...
std::vector<Numbers> a;
//fill the vector a and set Numbers::position of each element accordingly...
struct {
bool operator()(const Numbers& a,const Numbers& b)const
{
return a.value < b.value;
}
} my_comparator;
std::sort(a.begin(),a.end(),my_comparator);
//...