【待完善】c++ stl sort的用法

目錄

 

1.聲明外部比較函數

2.聲明比較類

3.重載類的比較運算符

4.Lambda表達式

5.筆試題


1.聲明外部比較函數

bool Less(const Student& s1, const Student& s2)
{
    return s1.name < s2.name; //從小到大排序
}
std::sort(sutVector.begin(), stuVector.end(), Less);

s1.name < s2.name //從小到大排序

s1.name > s2.name//從大到小排序

2.聲明比較類

struct Less
{
    bool operator()(const Student& s1, const Student& s2)
    {
        return s1.name < s2.name; //從小到大排序
    }
};

std::sort(sutVector.begin(), stuVector.end(), Less());

3.重載類的比較運算符

4.Lambda表達式

std::sort(sutVector.begin(), stuVector.end(), [](const Student& s1, const Student& s2)->bool
{
    return s1.name < s2.name;
});

https://www.cnblogs.com/DswCnblog/p/5629165.html c++11Lambda表達式

https://www.cnblogs.com/jimodetiantang/p/9016826.html c++11之Lambda表達式

https://blog.csdn.net/lixiaogang_theanswer/article/details/80905445 c++11之Lambda函數的詳細使用

5.筆試題

   完成Mycomp,使得數組a按字符串長度排序,字符串長度一樣時,按字符串大小排序。

int main()
{
    std::vector<std::string> strs;
    std::sort(strs.begin(), strs.end(), MyComp() );
    struct MyComp
    {

    };
}

答案:

struct MyComp
    {
        bool operator()(const std::string &str1, const std::string &str2)
        {
            int len1 = str1.length();
            int len2 = str2.length();
            if(len1!=len2)
            {
                return (len1<len2);
            }
            return (str1.compare(str2)<0);
        }
    };

測試代碼:

int main()
{
    std::vector<std::string> strs;
    strs.push_back("hi");
    strs.push_back("hello");
    strs.push_back("world");
    strs.push_back("123");
    strs.push_back("bcde");
    strs.push_back("bbcd");
    std::sort(strs.begin(), strs.end(), MyComp() );
    for (int i = 0; i < 6; i++)
    {
        cout<<strs[i]<<endl;
    }
}

https://www.cnblogs.com/nihow/p/4297102.html  C++<algorithm>中sort的比較函數寫法

https://blog.csdn.net/soul_97/article/details/78183429 STL庫函數sort的用法詳解

https://www.cnblogs.com/moujun1001/p/9629112.html stl之sort函數使用方法

http://www.cplusplus.com/reference/algorithm/sort/ c++ reference std::sort

https://blog.csdn.net/wanghaofeng/article/details/7317442 STL sort使用及重載

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章