我想使用stl排序算法对一些数字进行排序,但我也想记住它们的初始位置。我有这样的数据结构:
struct Numbers {
int position;
int value;
};我创造了这样的数字向量:
vector<Numbers> a;如何使用stl排序算法,以便根据值对数据结构进行排序?
发布于 2013-10-27 17:12:13
您也可以使用函子:
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; }
);发布于 2013-10-27 17:08:52
您需要重载"<“操作符,如下所示:
bool Numbers::operator<(Numbers temp)
{
return value < temp.value;
}发布于 2013-10-27 17:12:18
使用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);
//...https://stackoverflow.com/questions/19620832
复制相似问题