1. 程式人生 > >sort()函式 ----排序

sort()函式 ----排序

需求:驗證sort()函式對拼音排序效果。

QT環境原始碼

#include <QCoreApplication>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <algorithm>
class userInfo{
public:
    userInfo(std::string pinyin):m_pinyin(pinyin){}

    std::string m_pinyin;

};

QList<userInfo*> userList = {};

bool compare_(userInfo* s1, userInfo* s2){
    return s1->m_pinyin < s2->m_pinyin;
}
int main(int argc, char *argv[])
{
    printf("========hello======\n");

    userInfo* p1 = new userInfo("zhangsan");
    userInfo* p2 = new userInfo("azhangsan");
    userInfo* p3 = new userInfo("liwuzhangsanhaa");
    userInfo* p4 = new userInfo("zhangsanuuha");
    userInfo* p5 = new userInfo("1lizhangsan");
    userInfo* p6 = new userInfo("zhangsanhhhh");

    userList.push_back(p1);
    userList.push_back(p2);
    userList.push_back(p3);
    userList.push_back(p4);
    userList.push_back(p5);
    userList.push_back(p6);
    std::sort(userList.begin(),userList.end(), compare_);

    QList<userInfo*>::iterator iter;
    for(iter = userList.begin(); iter != userList.end(); ++iter)
    {
        printf("pinyin:%s\n",(*iter)->m_pinyin.c_str());
    }

    return 0;
}

驗證結果:

Starting /home/user/build-TestList-Desktop_Qt_5_9_5_GCC_64bit-Debug/TestList...
========hello======
pinyin:1lizhangsan
pinyin:azhangsan
pinyin:liwuzhangsanhaa
pinyin:zhangsan
pinyin:zhangsanhhhh
pinyin:zhangsanuuha