标题直接看总代码即可
引用头文件
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
定义初始化一个数组
vector <int> temp = {1,3,2,4};
定义排序用的结构体与数组,记录原索引与value
typedef struct
{
int index;
int value;
}sort_st;
vector <sort_st> sort_array(temp.size());
自己编写排序规则函数
bool compare(sort_st a,sort_st b)
{
return a.value<b.value; //升序排列,如果改为return a.value<b.value,则为降序
}
排序
sort(sort_array.begin(),sort_array.end(),compare);
总代码
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
typedef struct
{
int index;
int value;
}sort_st;
bool compare(sort_st a,sort_st b)
{
return a.value<b.value; //升序排列,如果改为return a.value<b.value,则为降序
}
int main()
{
vector <int> temp = {1,3,2,4};
vector <sort_st> sort_array(temp.size());
for(int i=0;i<temp.size();++i){
sort_array[i].index=i;
sort_array[i].value=temp[i];
}
sort(sort_array.begin(),sort_array.end(),compare);
for(int i=0;i<temp.size();++i){
cout<<sort_array[i].value<<' '<<sort_array[i].index<<endl;
}
return 0;
}
执行结果
1 0
2 2
3 1
4 3
我是杰出的小茄子,不拖泥带水
这篇博客展示了如何使用C++实现快速排序算法,并在排序过程中记录每个元素的原始索引。通过自定义排序规则函数,博主提供了一个完整的代码示例,包括初始化数组、定义结构体来存储索引和值,以及展示排序后的执行结果。
1482





