我是靠谱客的博主 乐观鱼,最近开发中收集的这篇文章主要介绍c++ sort用法 std::sort,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

unction template
<algorithm>

std::sort

default (1)
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Sort elements in range
Sorts the elements in the range  [first,last) into ascending order.

The elements are compared using  operator< for the first version, and  comp for the second.

Equivalent elements are not guaranteed to keep their original relative order (see  stable_sort).

Parameters

first, last
Random-access iterators to the initial and final positions of the sequence to be sorted. The range used is [first,last), which contains all the elements between  first and  last, including the element pointed by  first but not the element pointed by  last.
RandomAccessIterator shall point to a type for which  swap is properly defined and which is both  move-constructible and  move-assignable.
comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific  strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 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;
}


Output:
myvector contains: 12 26 32 33 45 53 71 80

最后

以上就是乐观鱼为你收集整理的c++ sort用法 std::sort的全部内容,希望文章能够帮你解决c++ sort用法 std::sort所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部