在编程中,我们经常需要对list进行排序。本文将从几个方面介绍如何对list进行排序,包括STL中的sort()函数、自定义比较函数进行排序、按字典序排序和按字符串长度排序。
一、使用STL中的sort()函数进行排序
STL中提供了sort()函数,其可以对list容器中的元素进行排序。sort()函数默认升序排序,对于list容器,按照字典序排序。下面是示例代码:
#include #include #include using namespace std; int main() { list mylist{"apple", "banana", "orange", "pear"}; mylist.sort(); for (string& s : mylist) cout << s << " "; return 0; }
上述代码中,我们创建了一个list容器,将其内容设定为{“apple”, “banana”, “orange”, “pear”},使用sort()函数对其进行排序,最后将排好序的容器输出。输出结果为:apple banana orange pear。
二、使用自定义比较函数进行排序
在有些情况下,我们需要按照自定义规则进行排序,此时我们可以使用sort()函数的第三个参数进行自定义比较。下面是示例代码:
#include #include #include using namespace std; bool mycompare(string s1, string s2) { return s1.size() < s2.size(); } int main() { list mylist{"apple", "banana", "orange", "pear"}; mylist.sort(mycompare); for (string& s : mylist) cout << s << " "; return 0; }
上述代码中,我们定义了一个自定义比较函数mycompare(),其按照字符串长度进行排序。使用sort()函数对mylist容器进行排序,最后将排好序的容器输出。输出结果为:pear apple banana orange。
三、按字典序排序
对于list容器,默认使用字典序进行排序。下面是示例代码:
#include #include #include using namespace std; int main() { list mylist{"apple", "banana", "orange", "pear"}; mylist.sort(); for (string& s : mylist) cout << s << " "; return 0; }
上述代码中,我们创建了一个list容器,将其内容设定为{“apple”, “banana”, “orange”, “pear”},使用sort()函数对其进行排序,最后将排好序的容器输出。输出结果为:apple banana orange pear。
四、按字符串长度排序
如果我们需要按照字符串长度进行排序,可以使用自定义比较函数,其比较规则为字符串长度。下面是示例代码:
#include #include #include using namespace std; bool mycompare(string s1, string s2) { return s1.size() < s2.size(); } int main() { list mylist{"apple", "banana", "orange", "pear"}; mylist.sort(mycompare); for (string& s : mylist) cout << s << " "; return 0; }
上述代码中,我们定义了一个自定义比较函数mycompare(),其按照字符串长度进行排序。使用sort()函数对mylist容器进行排序,最后将排好序的容器输出。输出结果为:pear apple banana orange。
在编程中,对list进行排序是非常常见的操作,本文介绍了使用STL中的sort()函数进行排序、使用自定义比较函数进行排序、按字典序排序和按字符串长度排序。在实际应用中,我们可以根据自己的需求选择合适的排序方法。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/277963.html