使用std::sort进行相关数组的排序笔记
一、相关的程序
-
程序首先创建一个num[ ]的索引数组,索引数量大小与数据数组的arr[ ]大小相关 通过std::sort ( RandomIt first, RandomIt last, Compare comp )排序 RandomIt first:排序的起始位置 RandomIt last:排序的终止位置( first 和 last 构成排序的范围) Compare comp:排序的比较函数 通过自己写的排序函数comp( )对数组arr[ ]的数据进行比较,然后对索引数组进行索引的排序,可以在不打乱arr[ ]数据情况下,通过数据的索引得到arr[ ]数据大小排序。 索引数组排列顺序是根据指向数据由小到大进行排列的
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
//数组mun[]是数组arr[]的数据索引标志数组
//数组arr[]是相关的数据数组
int num[12] ={
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int arr[12] = {
5, 6, 7, 2, 3, 4, 0, 12, 2, 34, 12, 6};
//comp函数用于比较arr[]数据的大小
bool comp (int i, int j) {
return(arr[i]<arr[j]); }
void print_main()
{
cout << "Hello" << endl;
printf("----- The index after sort of arr[] -----
");
printf("----- The index order from to smallest to largest -----
");
printf("
");
printf("----- Printf the index -----
");
//重新排序后的索引是由根据指向数据由小到大排列的,这边打印的索引index数组num[ ]是由大到小进行打印(i--)
std::sort (num, num + 12 + 1, comp);
for (int i = 12; i > 0; i--)
{
printf("%d ", num[i]);
}
printf("
");
printf("----- Printf the arr using the index -----
");
//重新排序后的索引是由根据指向数据由小到大排列的,这边索引index指向数据是由大到小进行排列(i--)
for (int i = 12; i > 0; i--)
{
int ind = num[i];
printf("%d ", arr[ind]);
}
printf("
");
printf("
");
/****************/
printf("----- Before sorting arr by std::sort -----
");
for (int i = 11; i >= 0; i--)
{
printf("%d ", arr[i]);
}
printf("
");
printf("----- After sorting arr by std::sort -----
");
std::sort (arr, arr + 12);
for (int i = 11; i >= 0; i--)
{
printf("%d ", arr[i]);
}
printf("
");
}
二、程序运行结果
下一篇:
推荐一份《阿里巴巴面试参考指南》
