站点图标 起风网

C++排序函数sort

一、sort函数的用法

二、两种用法

两个参数用法(此时默认升序排列)
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int i;
    int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };

    for(i = 0; i < 10; i++) {
        cout << a[i] << " ";  //2 4 1 23 5 76 0 43 24 65
    }

    sort(a, a + 10);

    for(i = 0; i < 10; i++) {
        cout << a[i] << " ";  //0 1 2 4 5 23 24 43 65 76
    }

    return 0;
}
三个参数的用法(可选升序或降序)

首先需要自定义一个比较函数:compare()

bool compare(int a, int b) {
    //return a < b; //升序排列
    return a > b;  //降序排列
}

这个函数告诉程序,到底是升序还是降序排列。

#include <iostream>
#include <algorithm>

using namespace std;

bool compare(int a, int b) {
    //return a < b; //升序排列
    return a > b;  //降序排列
}

int main()
{
    int i;
    int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };

    for(i = 0; i < 10; i++) {
        cout << a[i] << " ";  //2 4 1 23 5 76 0 43 24 65
    }
    cout << endl;

    sort(a, a + 10, compare);  //这里不需要对compare传参,这是规则

    for(i = 0; i < 10; i++) {
        cout << a[i] << " ";  //76 65 43 24 23 5 4 2 1 0
    }

    return 0;
}

也可以不自定义一个比较函数,可以调用标准库里的模板:

这里会用到:functional头文件,所以别忘了加上#include <functional>

functional提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to、not_equal_to、greater、greater_equal、less、less_equal。对于这个问题来说,greater和less就足够了,直接拿过来用:

# include <iostream>
# include <algorithm>
# include <functional>

using namespace std;

int main()
{
    int i;
    int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };

    for (i = 0; i < 10; i++) {
        cout << a[i] << " ";  //2 4 1 23 5 76 0 43 24 65
    }
    cout << endl;

    //升序
    sort( a, a + 10, less<int>() );

    for (i = 0; i < 10; i++) {
        cout << a[i] << " ";  //0 1 2 4 5 23 24 43 65 76
    }

    cout << endl;

    //降序
    sort( a, a + 10, greater<int>() );

    for (i = 0; i < 10; i++) {
        cout << a[i] << " ";  //76 65 43 24 23 5 4 2 1 0
    }
    cout << endl;

    return 0;
}

三、对字符串型的数据排序

1.使用迭代器,顺序排列:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string str = "hello world";

    sort( str.begin(), str.end() );

    cout << str;  //空格dehllloorw //注意空格

    return 0;
 }

2.使用反向迭代器,逆序排列:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string str = "hello world";

    sort( str.rbegin(), str.rend() );

    cout << str;  //wroolllhed空格 //注意空格

    return 0;
 }

使用IDE:CodeBlocks

结语:文章有错误或不足,欢迎评论,希望轻拍,一起进步哦!

END!

退出移动版