c++STL之常用排序算法

时间:2022-07-24
本文章向大家介绍c++STL之常用排序算法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

sort:对容器元素进行排序

random_shuffle:洗牌,指定范围内的元素随机调整次序

merge:容器元素合并,并存储到另一容器中

reverse:反转指定范围内的元素

1.sort

#include<iostream>
using namespace std;
#include <algorithm>
#include <vector>
#include <functional>

//常用排序算法 sort
void myPrint(int val)
{
    cout << val << " ";
}
void test01()
{
    vector<int>v;
    
    v.push_back(10);
    v.push_back(30);
    v.push_back(50);
    v.push_back(20);
    v.push_back(40);

    //利用sort进行升序
    sort(v.begin(), v.end());
    for_each(v.begin(), v.end(), myPrint);
    cout << endl;

    //改变为 降序
    sort(v.begin(), v.end(), greater<int>());
    for_each(v.begin(), v.end(), myPrint);
    cout << endl;
}

int main() {

    test01();

    system("pause");

    return 0;
}

2.random_shuffle

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <ctime>

//常用排序算法  random_shuffle

void myPrint(int val)
{
    cout << val << " ";
}

void test01()
{
    srand((unsigned int)time(NULL));

    vector<int>v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    //利用洗牌 算法 打乱顺序
    random_shuffle(v.begin(), v.end());

    for_each(v.begin(), v.end(), myPrint);
    cout << endl;
}

int main() {

    test01();

    system("pause");

    return 0;
}

3.merge

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>

void myPrint(int val)
{
    cout << val << " ";
}

//常用排序算法 merge
void test01()
{
    vector<int>v1;
    vector<int>v2;

    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
        v2.push_back(i+1);
    }

    //目标容器
    vector<int>vTarget;

    //提前给目标容器分配空间
    vTarget.resize(v1.size() + v2.size());

    merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());

    for_each(vTarget.begin(), vTarget.end(), myPrint);
    cout << endl;

}

int main() {

    test01();

    system("pause");

    return 0;
}

4.reverse

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>

//常用排序算法  reverse
void myPrint(int val)
{
    cout << val << " ";
}
void test01()
{
    vector<int>v;
    v.push_back(10);
    v.push_back(30);
    v.push_back(50);
    v.push_back(20);
    v.push_back(40);

    cout << "反转前: " << endl;
    for_each(v.begin(), v.end(), myPrint);
    cout << endl;

    cout << "反转后: " << endl;
    reverse(v.begin(), v.end());
    for_each(v.begin(), v.end(), myPrint);
    cout << endl;

}

int main() {

    test01();

    system("pause");

    return 0;
}