美文网首页
9.常用排序算法-sort

9.常用排序算法-sort

作者: lxr_ | 来源:发表于2021-05-12 09:43 被阅读0次
#include<iostream>
using namespace std;

#include<vector>
#include<algorithm>
#include<time.h>

//sort(iterator begin,iterator end,_Pred)//对容器内元素进行排序,找到返回指定位置迭代器,未找到返回结束迭代器end
//random_shuffle //洗牌,指定范围内的元素随机调整次序
//merge//容器元素合并,并存储到另一容器中
//reverse//反转指定范围的元素

class SortRule
{
public:
    bool operator()(int val1, int val2)
    {
        return val1 > val2;
    }
};
class MyPrint
{
public:
    void operator()(int val)
    {
        cout << val << " ";
    }
};
void test0901()
{
    vector<int> v;

    for (int i = 0; i < 10; i++)
    {
        v.push_back(rand() % 100);
    }

    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << (*it) << " ";
    }
    cout << endl;

    sort(v.begin(), v.end());//默认升序排序

    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << (*it) << " ";
    }
    cout << endl;

    sort(v.begin(), v.end(), SortRule());//或者使用内建函数对象  greater<int>()实现降序排序
    for_each(v.begin(), v.end(), MyPrint());//可以使用仿函数或者普通函数
}

int main()
{
    srand((unsigned int)time(NULL));
    test0901();

    system("pause");
    return 0;
}

相关文章

网友评论

      本文标题:9.常用排序算法-sort

      本文链接:https://www.haomeiwen.com/subject/ecwirltx.html