使用sort函数对数组排序

风流意气都作罢 提交于 2020-01-10 05:15:35

使用sort函数对数组排序

按照升序将数组的数字排序:

/********************************************************

@File  sort function.

@Description sort from small to large.

@Author  Eric Wang

@Date:   2020-01-08

@Association: Harbin Institute of Technology, Shenzhen.

*********************************************************/


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


bool compare(int& x, int& y)
{
    return x < y;
}

class Solution
{
public:
    int singleNumber(vector<int>& nums)
    {
        sort(nums.begin(), nums.end(), compare);
    }

};

int main(int argc, char** argv)
{
    Solution solution;

    vector<int> num = {1, 2, 1, 3, 5};

    solution.singleNumber(num);

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

}

输出结果如下:
结果输出

需要注意的,compare函数需要定义为全局函数,或者类静态成员函数。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!