转发列表 在STL中实现了单链表。forward list是从C++11引入的,在插入、移除和移动操作(如排序)中,它比其他容器更有用,并且允许以时间常量插入和移除元素。它与list的不同之处在于,forward list只跟踪下一个元素的位置,而list同时跟踪下一个和上一个元素。
null
转发列表::排序()
sort()函数用于通过更改容器元素的位置对其进行排序。 语法:
1. forwardlistname.sort() Parameters : No parameters are passed. Result : The elements of the container are sorted in ascending order.2. forwardlistname.sort(predicate) Parameters : predicate is used to define your own custom sorting function, it will return boolean output Result : The elements of the container sorted in the order as per predicate function
例如:
Input : myflist{1, 5, 3, 2, 4}; myflist.sort();Output : 1, 2, 3, 4, 5Input : myflist{"This","is","Geeksforgeeks"}; myflist.sort();Output : Geekforgeeks, This, is
错误和异常 1.它有一个基本的无例外抛出保证。
CPP
// SORTING INTEGERS // CPP program to illustrate // Implementation of sort() function #include <iostream> #include <forward_list> using namespace std; int main() { // forward list declaration of integer type forward_list< int > myflist{1, 5, 3, 2, 4}; // sort function myflist.sort(); // printing the forward list after sort for ( auto it = myflist.begin(); it != myflist.end(); ++it) cout << ' ' << *it; return 0; } |
输出:
1 2 3 4 5
CPP
// SORTING STRINGS // CPP program to illustrate // Implementation of sort() function #include <iostream> #include <forward_list> #include <string> using namespace std; int main() { // forward list declaration of string type forward_list<string> myflist{ "This" , "is" , "Geeksforgeeks" }; // sort function myflist.sort(); // printing the forward list after sort for ( auto it = myflist.begin(); it != myflist.end(); ++it) cout << ' ' << *it; return 0; } |
输出:
Geeksforgeeks This is
时间复杂性: O(nlogn)
C++
// SORTING STRINGS USING CUSTOM COMPARATOR FUNCTION // CPP program to illustrate // Implementation of sort() function #include <iostream> #include <forward_list> #include <string> using namespace std; bool comparator(string a, string b) { return a.length() <= b.length(); } int main() { // forward list declaration of string type forward_list<string> myflist{ "This" , "is" , "Geeksforgeeks" }; // sort function myflist.sort(comparator); // printing the forward list after sort for ( auto it = myflist.begin(); it != myflist.end(); ++it) cout << ' ' << *it; return 0; } |
输出:
is This Geeksforgeeks
时间复杂度–O(nlog(n))
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END