STL排序一览以及 Lambda表达式

1、首先介绍lambda表达式:

C++11的一大亮点就是引入了Lambda表达式。利用Lambda表达式,可以方便的定义和创建匿名函数

完整声明格式如下:

[capture list] (params list) mutable exception-> return type { function body }
  1. capture list:捕获外部变量列表
  2. params list:形参列表
  3. mutable指示符:用来说用是否可以修改捕获的变量
  4. exception:异常设定
  5. return type:返回类型
  6. function body:函数体

序号 格式
1 [capture list] (params list) -> return type {function body}  std::sort中默认bool返回值 
2 [capture list] (params list) {function body}  表示两元素符合某个条件则交换
3 [capture list] {function body} 

!!!重点,在std::sort中的应用

2、降序排列

sort(lbvec.begin(), lbvec.end(), [](int a, int b) -> bool { return a < b; });   // Lambda表达式
sort(lbvec.begin(), lbvec.end(), [](int a, int b) { return a < b; });   // Lambda表达式  

  • 若需对vector, string, deque, 或 array容器进行全排序,你可选择sort或stable_sort;
  • 若只需对vector, string, deque, 或 array容器中取得top n的元素,部分排序partial_sort是首选.
  • 若对于vector, string, deque, 或array容器,你需要找到第n个位置的元素或者你需要得到top n且不关系top n中的内部顺序,nth_element是最理想的;
  • 若你需要从标准序列容器或者array中把满足某个条件或者不满足某个条件的元素分开,你最好使用partition或stable_partition;
  • 若使用的list容器,你可以直接使用partition和stable_partition算法,你可以使用list::sort代替sort和stable_sort排序。若你需要得到partial_sort或nth_element的排序效果,你必须间接使用。正如上面介绍的有几种方式可以选择

3、大小写转换函数

 transform(s.begin(),s.end(),s.begin(),::toupper)

 transform(s.begin(),s.end(),s.begin(),::tolower)

猜你喜欢

转载自blog.csdn.net/qq_24950821/article/details/80294659