C++ 数据结构的排序算法
C++ Sort Algorithm for data structures
我想使用 stl 排序算法对一些数字进行排序,但我也想记住它们的初始位置。我有一个这样的数据结构:
struct Numbers {
int position;
int value;
};
我创建了一个这样的数字向量:
vector<Numbers> a;
如何使用 stl 排序算法,以便根据值对数据结构进行排序?
您也可以
使用函子:
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; }
);
您需要
重载"<"运算符,如下所示:
bool Numbers::operator<(Numbers temp)
{
return value < temp.value;
}
使用std::sort
并提供自定义比较器(模板参数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);
//...
相关文章:
- C++选择排序算法中的逻辑错误
- 排序算法c++
- 下面是排序算法O(n)吗
- 为什么我的排序算法会更改数组值
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 排序算法问题(购买商店物品)(崩溃)
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 为什么在此排序算法实现中,向量明显比数组慢?
- C++ 多线程 - 与线程合并排序的算法替代
- C++中合并排序算法的奇怪行为
- 如果要求比较器是严格的总排序,而不仅仅是严格的弱排序,C++标准算法会更快吗?
- 我的排序算法程序中的堆错误
- 运行合并排序递归算法时EXC_BAD_ACCESS错误
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 解释一下这个排序算法是如何工作的?
- 检查向量是否使用除法和阻抗算法进行排序
- 使用sort()算法C 排序对象列表
- 算法排序1101001011
- 克鲁斯卡尔算法(排序)
- 用STL算法排序结构的动态数组