目录
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使用及重载