1.sort
头文件:#include <algorithm>
1.1使用sort对数组进行排序
#include<iostream>
#include<algorithm>
int main()
{
int a[10] = { 9,6,3,8,5,2,7,4,1,0 };
std::cout << "before sort: " << std::endl;
for (int i = 0; i<10; i++)
std::cout << a[i] << " ";
std::sort(a, a + 10);
std::cout << std::endl << "after sort: " << std::endl;
for (int i = 0; i<10; i++)
std::cout << a[i] << " ";
return 0;
}
----运行结果:
before sort:
9 6 3 8 5 2 7 4 1 0
after sort:
0 1 2 3 4 5 6 7 8 9 请按任意键继续. . .
上述做法默认是升序排列,如果想要降序排列,需要自己编写compare函数,作为sort函数的第三个参数传入。
#include<iostream>
#include<algorithm>
bool cmp(const int &a, const int &b)
{
return a > b;
}
int main()
{
int a[10] = { 9,6,3,8,5,2,7,4,1,0 };
std::cout << "before sort: " << std::endl;
for (int i = 0; i<10; i++)
std::cout << a[i] << " ";
std::sort(a, a + 10, cmp);
std::cout << std::endl << "after sort: " << std::endl;
for (int i = 0; i<10; i++)
std::cout << a[i] << " ";
return 0;
}
----运行结果:
before sort:
9 6 3 8 5 2 7 4 1 0
after sort:
9 8 7 6 5 4 3 2 1 0 请按任意键继续. . .
1.2 使用sort对vector进行排序
用法同1.1类似,只是需要传入vector的迭代器作为参数。
#include <iostream>
#include <algorithm>
#include <vector>
bool cmp(const int &a, const int &b)
{
return a > b;
}
int main()
{
std::vector<int> a = { 9,6,3,8,5,2,7,4,1,0 };
std::cout << "before sort: " << std::endl;
for (auto i : a)
std::cout << i << " ";
std::sort(a.begin(), a.end());
std::cout << std::endl << "升序排列:" << std::endl;
for (auto i : a)
std::cout << i << " ";
std::cout << std::endl << "降序排列:" << std::endl;
std::sort(a.begin(), a.end(), cmp);
for (auto i : a)
std::cout << i << " ";
return 0;
}
before sort:
9 6 3 8 5 2 7 4 1 0
升序排列:
0 1 2 3 4 5 6 7 8 9
降序排列:
9 8 7 6 5 4 3 2 1 0 请按任意键继续. . .
若想实现降序排列,也可以用reverse将升序排列好的结果,翻转一下。但这样的效率不高。reverse函数的用法也是类似。
reverse(a.begin(),a.end()); // 翻转vector
2.部分排序partial_sort
待更新。。