首页 > 编程语言 > 详细

C++ sort() 用法介绍

时间:2021-04-18 11:28:57      阅读:21      评论:0      收藏:0      [点我收藏+]

std:: sort()

所属头文件

<algorithm>

介绍

可以对某个范围进行排序

不保证等效元素保持其原始相对顺序

参数

first, last

代表需要排序内容的开始位置和结尾,范围是 [first, last)

comp

一个函数,其参数有两个,接受范围内的两个元素作为参数,返回的值表示第一个参数所表示的元素是否要在第二个参数前面。返回一个 bool 类型
既可以是一个函数指针,也可以是一个函数对象

案例

来自 cplusplus.com

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ‘ ‘ << *it;
  std::cout << ‘\n‘;

  return 0;
}

C++ sort() 用法介绍

原文:https://www.cnblogs.com/HamFav/p/14459048.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!