STL中的转发列表实现单链接列表。从C++ 11引入的前向列表在插入,删除和移动操作(如排序)方面比其他容器有用,并且允许时间常数插入和删除元素。它与列表的不同之处在于前向列表会跟踪对象的位置仅list的下一个元素同时跟踪下一个和上一个元素。
forward_list::sort()
sort()函数用于通过更改容器的位置来对容器的元素进行排序。
用法:
forwardlistname.sort() 参数: No parameters are passed. Result: The elements of the container are sorted in ascending order.
例子:
Input :myflist{1, 5, 3, 2, 4};
         myflist.sort();
Output:1, 2, 3, 4, 5
Input :myflist{"This","is","Geeksforgeeks"};
         myflist.sort();
Output:Geekforgeeks, This, is
错误和异常
1.它具有基本的无异常抛出保证。
2.传递参数时显示错误。
// 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
// 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(登录)
相关用法
注:本文由纯净天空筛选整理自AyushSaxena大神的英文原创作品 std::forward_list::sort() in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
