清单 C++中使用的容器以非连续的方式存储数据,通常,数组和向量本质上是连续的,因此插入和删除操作与列表中的插入和删除选项相比更昂贵。
null
列表::排序()
sort()函数用于通过更改容器元素的位置对其进行排序。
语法:
listname.sort() Parameters : No parameters are passed. Result : The elements of the container are sorted in ascending order.
例如:
Input : mylist{1, 5, 3, 2, 4}; mylist.sort(); Output : 1, 2, 3, 4, 5 Input : mylist{"hi", "bye", "thanks"}; mylist.sort(); Output : bye, hi, thanks
错误和异常
1.它有一个基本的无例外抛出保证。 2.传递参数时显示错误。
// SORTING INTEGERS // CPP program to illustrate // Implementation of sort() function #include <iostream> #include <list> using namespace std; int main() { // list declaration of integer type list< int > mylist{ 1, 5, 3, 2, 4 }; // sort function mylist.sort(); // printing the list after sort for ( auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0; } |
输出:
1 2 3 4 5
// SORTING STRINGS // CPP program to illustrate // Implementation of sort() function #include <iostream> #include <list> #include <string> using namespace std; int main() { // list declaration of string type list<string> mylist{ "hi" , "bye" , "thanks" }; // sort function mylist.sort(); // printing the list after sort for ( auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0; } |
输出:
bye hi thanks
时间复杂性: O(nlogn)
类似功能: C++ STL中的排序
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END