C++头文件algorithm中的函数功能详解

目录1. 不修改内容的序列操作(1)all_of(2)any_of(3)none_of(6)find_if(7)find_if_not(8)find_end(10)adjacent_find(12)count_if(15)is_permutation(16)search2. 修改内容的序列操作(1)copy(2)copy_n(3)copy_if(4)copy_backward(5)move(6)move_backward(7)swap(8)swap_ranges(9)iter_swap(10)transform(11)replace(13)replace_copy(14)replace_copy_if(15)fill(16)fill_n3. 划分操作(Partitions)4. 排序操作(sorting)5. 二分查找操作(Binary search)6. 集合(Merge)7. 堆操作8. 最小最大值操作9. 其他

C++中的算法都是通过函数模板实现,所以STL的数据结构,甚至是自己定义的数据结构基本都可以调用内置算法。掌握C++内置算法,可以帮助我们节省大量的时间!

1. 不修改内容的序列操作

(1)all_of

查找是否所有元素满足条件。

在range[first,last)中,所有pred都为真,或者range范围为空,返回true,否则返回false。

template <class InputIterator, class UnaryPredicate>  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);

举例:

#include <iostream>     // std::cout#include <algorithm>    // std::all_of#include<list>int main () {  //std::array<int,8> foo = {3,5,7,11,13,17,19,23};  std::list<int> foo = {3,5,7,11,13,17,19,23};  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )    std::cout << "All the elements are odd numbers.\n";//奇数  return 0;}

(2)any_of

查找是否有元素满足条件。

在range[first,last)中,pred至少有一个为真,或者range范围为空,返回true,否则返回false。用法同all_of。

template <class InputIterator, class UnaryPredicate>  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

(3)none_of

查找是否所有元素都不满足条件。

在range[first,last)中,pred没有一个为真,或者range范围为空,返回true,否则返回false。用法同all_of。

template <class InputIterator, class UnaryPredicate>  bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred);

(4)for_each

对range [first,last)中的每一个元素,都执行fn函数操作。

fn可以是普通函数也可以是仿函数(函数对象)。 fn后面不可以添加括号

template <class InputIterator, class Function>   Function for_each (InputIterator first, InputIterator last, Function fn);

代码举例:

#include <iostream>     // std::cout#include <algorithm>    // std::for_each#include <vector>       // std::vectorvoid myfunction (int i) {  // function:普通函数  std::cout << ' ' << i;}struct myclass {           // function object type:,仿函数,或者函数对象  void operator() (int i) {std::cout << ' ' << i;}} myobject;int main () {  std::vector<int> myvector;  myvector.push_back(10);  myvector.push_back(20);  myvector.push_back(30);  std::cout << "myvector contains:";  for_each (myvector.begin(), myvector.end(), myfunction);  std::cout << '\n';  // or:  std::cout << "myvector contains:";  for_each (myvector.begin(), myvector.end(), myobject);  std::cout << '\n';  return 0;}

(5)find

查找第一个和所提供变量相同的元素。

从 range [first,last)依次寻找元素,如果找到第一个与val相同相同的元素,则返回它的迭代器,否则返回last的迭代器。

template <class InputIterator, class T>   InputIterator find (InputIterator first, InputIterator last, const T& val);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::find#include <vector>       // std::vectorint main () {  // using std::find with array and pointer:  int myints[] = { 10, 20, 30, 40 };  int * p;  p = std::find (myints, myints+4, 30);  if (p != myints+4)    std::cout << "Element found in myints: " << *p << '\n';  else    std::cout << "Element not found in myints\n";  // using std::find with vector and iterator:  std::vector<int> myvector (myints,myints+4);  std::vector<int>::iterator it;  it = find (myvector.begin(), myvector.end(), 30);  if (it != myvector.end())    std::cout << "Element found in myvector: " << *it << '\n';  else    std::cout << "Element not found in myvector\n";  return 0;}

输出:

Element found in myints: 30Element found in myvector: 30

(6)find_if

查找第一个满足条件的元素。

从 range [first,last)依次寻找元素,如果找到第一个使得pred为真的元素,则返回它的迭代器,否则返回last迭代器。

template <class InputIterator, class UnaryPredicate>   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

代码举例:

寻找第一个奇数

#include <iostream>     // std::cout#include <algorithm>    // std::find_if#include <vector>       // std::vectorbool IsOdd (int i) {  return ((i%2)==1);}int main () {  std::vector<int> myvector;  myvector.push_back(10);  myvector.push_back(25);  myvector.push_back(40);  myvector.push_back(55);  std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);  std::cout << "The first odd value is " << *it << '\n';//奇数  return 0;}

输出:

The first odd value is 25

(7)find_if_not

查找第一个不满足条件的元素。

从 range [first,last)依次寻找元素,如果找到第一个使得pred为假的元素,则返回它的迭代器,否则返回last迭代器。

template <class InputIterator, class UnaryPredicate>   InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred);

代码举例:

寻找第一个偶数

#include <iostream>     // std::cout#include <algorithm>    // std::find_if_not#include <array>        // std::arrayint main () {  std::array<int,5> foo = {1,2,3,4,5};  std::array<int,5>::iterator it =    std::find_if_not (foo.begin(), foo.end(), [](int i){return i%2;} );  std::cout << "The first even value is " << *it << '\n';  return 0;}

输出:

The first even value is 2

(8)find_end

模板1:查找最后一个相同的序列。

在range [first1,last1) 去寻找[first2,last2)的元素,如果找到最后一个(不是第一个)被匹配的元素,则范围第一个被匹配的迭代器,否则范围last1的迭代器。

模板2:查找最后一个满足条件的序列。

在range [first1,last1) 去寻找[first2,last2)的元素,如果找到最后一个(不是第一个)满足pred条件的元素,则范围第一个被匹配的迭代器,否则范围last1的迭代器。

//equality (1)template <class ForwardIterator1, class ForwardIterator2>   ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1,                              ForwardIterator2 first2, ForwardIterator2 last2);//predicate (2)template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>   ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1,                              ForwardIterator2 first2, ForwardIterator2 last2,                              BinaryPredicate pred);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::find_end#include <vector>       // std::vectorbool myfunction (int i, int j) {  return (i==j);}int main () {  int myints[] = {1,2,3,4,5,1,2,3,4,5};  std::vector<int> haystack (myints,myints+10);  int needle1[] = {1,2,3};  // using default comparison:  std::vector<int>::iterator it;  it = std::find_end (haystack.begin(), haystack.end(), needle1, needle1+3);  if (it!=haystack.end())    std::cout << "needle1 last found at position " << (it-haystack.begin()) << '\n';  int needle2[] = {4,5,1};  // using predicate comparison:  it = std::find_end (haystack.begin(), haystack.end(), needle2, needle2+3, myfunction);  if (it!=haystack.end())    std::cout << "needle2 last found at position " << (it-haystack.begin()) << '\n';  return 0;}

输出:

needle1 last found at position 5needle2 last found at position 3

(9)find_first_of

和find_end类似,只不过它是寻找第一个匹配的元素。

//equality (1)template <class InputIterator, class ForwardIterator>   InputIterator find_first_of (InputIterator first1, InputIterator last1,                                   ForwardIterator first2, ForwardIterator last2);//predicate (2)template <class InputIterator, class ForwardIterator, class BinaryPredicate>   InputIterator find_first_of (InputIterator first1, InputIterator last1,                                   ForwardIterator first2, ForwardIterator last2,                                   BinaryPredicate pred);

(10)adjacent_find

模板1:从范围 range [first,last)中寻找连续相同元素。

模板2:找到满足条件pred的迭代器。

如果找到,则范围范围内的第一个满足的迭代器,否则范围last的迭代器。

//equality (1)template <class ForwardIterator>   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last);//predicate (2)template <class ForwardIterator, class BinaryPredicate>   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last,                                  BinaryPredicate pred);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::adjacent_find#include <vector>       // std::vectorbool myfunction (int i, int j) {  return (i==j);}int main () {  int myints[] = {5,20,5,30,30,20,10,10,20};  std::vector<int> myvector (myints,myints+8);  std::vector<int>::iterator it;  // using default comparison:  it = std::adjacent_find (myvector.begin(), myvector.end());  if (it!=myvector.end())    std::cout << "the first pair of repeated elements are: " << *it << '\n';  //using predicate comparison:  it = std::adjacent_find (++it, myvector.end(), myfunction);//从上一个已经找到的地方开始  if (it!=myvector.end())    std::cout << "the second pair of repeated elements are: " << *it << '\n';  return 0;}

输出:

the first pair of repeated elements are: 30the second pair of repeated elements are: 10

(11)count

在range [first,last)中,计算与val相同的元素个数。

template <class InputIterator, class T>  typename iterator_traits<InputIterator>::difference_type    count (InputIterator first, InputIterator last, const T& val);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::count#include <vector>       // std::vectorint main () {  // counting elements in array:  int myints[] = {10,20,30,30,20,10,10,20};   // 8 elements  int mycount = std::count (myints, myints+8, 10);  std::cout << "10 appears " << mycount << " times.\n";  // counting elements in container:  std::vector<int> myvector (myints, myints+8);  mycount = std::count (myvector.begin(), myvector.end(), 20);  std::cout << "20 appears " << mycount  << " times.\n";  return 0;}

输出:

10 appears 3 times.20 appears 3 times.

(12)count_if

在range [first,last)中,计算让pred为真的元素个数。

template <class InputIterator, class UnaryPredicate>  typename iterator_traits<InputIterator>::difference_type    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::count_if#include <vector>       // std::vectorbool IsOdd (int i) { return ((i%2)==1); }int main () {  std::vector<int> myvector;  for (int i=1; i<10; i++) myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9  int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);  std::cout << "myvector contains " << mycount  << " odd values.\n";  return 0;}

输出:

myvector contains 5 odd values.

(13)mismatch

找出两个序列不匹配的开始点,或者找出两个序列不满足条件pred的开始点。

模板1:first2与range [first1,last1) 范围内的元素对比,返回第一个都不匹配的迭代器组pair(first1, first2)。

模板2:first2与range [first1,last1) 范围内的元素对比,返回第一个不满足条件pred的迭代器组pair(first1, first2)。

//equality (1)template <class InputIterator1, class InputIterator2>  pair<InputIterator1, InputIterator2>    mismatch (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2);//predicate (2)template <class InputIterator1, class InputIterator2, class BinaryPredicate>  pair<InputIterator1, InputIterator2>    mismatch (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2, BinaryPredicate pred);

代码举例:

#include <iostream>     // std::cout#include <algorithm>    // std::mismatch#include <vector>       // std::vector#include <utility>      // std::pairbool mypredicate (int i, int j) {  return (i==j);}int main () {  std::vector<int> myvector;  for (int i=1; i<6; i++) myvector.push_back (i*10); // myvector: 10 20 30 40 50  int myints[] = {10,20,80,320,1024};                //   myints: 10 20 80 320 1024  std::pair<std::vector<int>::iterator,int*> mypair;  // using default comparison:  mypair = std::mismatch (myvector.begin(), myvector.end(), myints);  std::cout << "First mismatching elements: " << *mypair.first;  std::cout << " and " << *mypair.second << '\n';  ++mypair.first; ++mypair.second;  // using predicate comparison:  mypair = std::mismatch (mypair.first, myvector.end(), mypair.second, mypredicate);  std::cout << "Second mismatching elements: " << *mypair.first;  std::cout << " and " << *mypair.second << '\n';  return 0;}

输出:

First mismatching elements: 30 and 80Second mismatching elements: 40 and 320

(14)equal

判断两个序列是否相等,或者满足条件pred。

如果两个序列都相等,或者都满足条件pred,则返回true。

//equality (1)template <class InputIterator1, class InputIterator2>  bool equal (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2);//predicate (2)template <class InputIterator1, class InputIterator2, class BinaryPredicate>  bool equal (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2, BinaryPredicate pred);

代码举例:

#include <iostream>     // std::cout#include <algorithm>    // std::equal#include <vector>       // std::vectorbool mypredicate (int i, int j) {  return (i==j);}int main () {  int myints[] = {20,40,60,80,100};               //   myints: 20 40 60 80 100  std::vector<int>myvector (myints,myints+5);     // myvector: 20 40 60 80 100  // using default comparison:  if ( std::equal (myvector.begin(), myvector.end(), myints) )    std::cout << "The contents of both sequences are equal.\n";  else    std::cout << "The contents of both sequences differ.\n";  myvector[3]=81;                                 // myvector: 20 40 60 81 100  // using predicate comparison:  if ( std::equal (myvector.begin(), myvector.end(), myints, mypredicate) )    std::cout << "The contents of both sequences are equal.\n";  else    std::cout << "The contents of both sequences differ.\n";  return 0;}

输出:

The contents of both sequences are equal.The contents of both sequences differ.

(15)is_permutation

permutation的意思是排列,组合的意思。也就是判断两个序列是不是只是重新组合了。

//equality (1)template <class ForwardIterator1, class ForwardIterator2>   bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,                        ForwardIterator2 first2);//predicate (2)template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>   bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,                        ForwardIterator2 first2, BinaryPredicate pred);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::is_permutation#include <array>        // std::arrayint main () {  std::array<int,5> foo = {1,2,3,4,5};  std::array<int,5> bar = {3,1,4,5,2};  if ( std::is_permutation (foo.begin(), foo.end(), bar.begin()) )    std::cout << "foo and bar contain the same elements.\n";  return 0;}

输出:

foo and bar contain the same elements.

(16)search

在 range [first1,last1)中寻找[first2,last2)子序列,找到则返回第一个相等或满足条件的迭代器,否则范围last1迭代器。

//equality (1)template <class ForwardIterator1, class ForwardIterator2>   ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,                            ForwardIterator2 first2, ForwardIterator2 last2);//predicate (2)template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>   ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,                            ForwardIterator2 first2, ForwardIterator2 last2,                            BinaryPredicate pred);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::search#include <vector>       // std::vectorbool mypredicate (int i, int j) {  return (i==j);}int main () {  std::vector<int> haystack;  // set some values:        haystack: 10 20 30 40 50 60 70 80 90  for (int i=1; i<10; i++) haystack.push_back(i*10);  // using default comparison:  int needle1[] = {40,50,60,70};  std::vector<int>::iterator it;  it = std::search (haystack.begin(), haystack.end(), needle1, needle1+4);  if (it!=haystack.end())    std::cout << "needle1 found at position " << (it-haystack.begin()) << '\n';  else    std::cout << "needle1 not found\n";  // using predicate comparison:  int needle2[] = {20,30,50};  it = std::search (haystack.begin(), haystack.end(), needle2, needle2+3, mypredicate);  if (it!=haystack.end())    std::cout << "needle2 found at position " << (it-haystack.begin()) << '\n';  else    std::cout << "needle2 not found\n";  return 0;}

输出:

needle1 found at position 3needle2 not found

(17)search_n

在 range [first,last)序列中,找出和val相等的个数,或者满足条件的pred的个数,找到则返回第一个满足条件的迭代器(指向最后一个满足计数的迭代器),否则返回last迭代器。

//equality (1)template <class ForwardIterator, class Size, class T>   ForwardIterator search_n (ForwardIterator first, ForwardIterator last,                             Size count, const T& val);//predicate (2)template <class ForwardIterator, class Size, class T, class BinaryPredicate>   ForwardIterator search_n ( ForwardIterator first, ForwardIterator last,                              Size count, const T& val, BinaryPredicate pred );

2. 修改内容的序列操作

(1)copy

复制range [first,last)的元素到result迭代器开始的序列中。result的范围不应该和[first,last)重叠。

template <class InputIterator, class OutputIterator>  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

代码举例:

#include <iostream>     // std::cout#include <algorithm>    // std::copy#include <vector>       // std::vectorint main () {  int myints[]={10,20,30,40,50,60,70};  std::vector<int> myvector (7);  std::copy ( myints, myints+7, myvector.begin() );  std::cout << "myvector contains:";  for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

myvector contains: 10 20 30 40 50 60 70

(2)copy_n

复制从first开始的n个元素,到result中。

template <class InputIterator, class Size, class OutputIterator>  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);

(3)copy_if

复制range [first,last)中满足条件pred的元素,到result中。

template <class InputIterator, class OutputIterator, class UnaryPredicate>  OutputIterator copy_if (InputIterator first, InputIterator last,                          OutputIterator result, UnaryPredicate pred);

(4)copy_backward

和copy类似,只不过copy_backward是从后面开始复制。

和copy一样,不允许重叠。

template <class BidirectionalIterator1, class BidirectionalIterator2>  BidirectionalIterator2 copy_backward (BidirectionalIterator1 first,                                        BidirectionalIterator1 last,                                        BidirectionalIterator2 result);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::copy_backward#include <vector>       // std::vectorint main () {  std::vector<int> myvector;  // set some values:  for (int i=1; i<=5; i++)    myvector.push_back(i*10);          // myvector: 10 20 30 40 50  myvector.resize(myvector.size()+3);  // allocate space for 3 more elements  std::copy_backward ( myvector.begin(), myvector.begin()+5, myvector.end() );  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

myvector contains: 10 20 30 10 20 30 40 50

(5)move

从[first,last)的元素移动到result中,原来的元素状态是有效的,但是元素的值不确定。

move移动时候,不应该有重叠。

template <class InputIterator, class OutputIterator>  OutputIterator move (InputIterator first, InputIterator last, OutputIterator result);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::move (ranges)#include <utility>      // std::move (objects)#include <vector>       // std::vector#include <string>       // std::stringint main () {  std::vector<std::string> foo = {"air","water","fire","earth"};  std::vector<std::string> bar (4);  // moving ranges:  std::cout << "Moving ranges...\n";  std::move ( foo.begin(), foo.begin()+4, bar.begin() );  std::cout << "foo contains " << foo.size() << " elements:";  std::cout << " (each in an unspecified but valid state)";  std::cout << '\n';  std::cout << "bar contains " << bar.size() << " elements:";  for (std::string& x: bar) std::cout << " [" << x << "]";  std::cout << '\n';  // moving container:  std::cout << "Moving container...\n";  foo = std::move (bar);  std::cout << "foo contains " << foo.size() << " elements:";  for (std::string& x: foo) std::cout << " [" << x << "]";  std::cout << '\n';  std::cout << "bar is in an unspecified but valid state";  std::cout << '\n';  return 0;}

输出:

Moving ranges…foo contains 4 elements: (each in an unspecified but valid state)bar contains 4 elements: [air] [water] [fire] [earth]Moving container…foo contains 4 elements: [air] [water] [fire] [earth]bar is in an unspecified but valid state

(6)move_backward

从range [first,last)中移动数据到result中,不过result是末尾。类似于copy_backward。

move_backward移动的时候,不应该有重叠。下面的示例没有重叠。

template <class BidirectionalIterator1, class BidirectionalIterator2>  BidirectionalIterator2 move_backward (BidirectionalIterator1 first,                                        BidirectionalIterator1 last,                                        BidirectionalIterator2 result);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::move_backward#include <string>       // std::stringint main () {  std::string elems[10] = {"air","water","fire","earth"};  // insert new element at the beginning:  std::move_backward (elems,elems+4,elems+5);  elems[0]="ether";  std::cout << "elems contains:";  for (int i=0; i<10; ++i)    std::cout << " [" << elems[i] << "]";  std::cout << '\n';  return 0;}

输出:

elems contains: [ether] [air] [water] [fire] [earth] [] [] [] [] []

(7)swap

C++11已经把该函数移到<utility>头文件中,已经不在<algorithm>中。

模板1:不修改地址,只交换值。

模板2:交换序列值的内容和大小。

交换两个元素的值,相应地址也会交换。

//non-array (1)template <class T> void swap (T& a, T& b)  noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);//array (2)template <class T, size_t N> void swap(T (&a)[N], T (&b)[N])  noexcept (noexcept(swap(*a,*b)));

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::swap#include <vector>       // std::vectorint main () {  int x=10, y=20;                              // x:10 y:20   std::cout<<"x add: "<<&x << "y add: "<< &y<<std::endl;  std::swap(x,y);                              // x:20 y:10  std::cout<<"x add: "<<&x << "y add: "<< &y<<std::endl;  //x:20 ,y: 10  std::vector<int> foo (4,x), bar (6,y);       // foo:4x20 bar:6x10  std::swap(foo,bar);                          // foo:6x10 bar:4x20  std::cout << "foo contains:";  for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  std::cout << "bar contains:";  for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

x add: 0x7ffc1528b7e8y add: 0x7ffc1528b7ecx add: 0x7ffc1528b7e8y add: 0x7ffc1528b7ecfoo contains: 10 10 10 10 10 10bar contains: 20 20 20 20

(8)swap_ranges

只交换一部分数据,从range [first1,last1) 对应位置,交换first2开始的值。

template <class ForwardIterator1, class ForwardIterator2>  ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,                                ForwardIterator2 first2);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::swap_ranges#include <vector>       // std::vectorint main () {  std::vector<int> foo (5,10);        // foo: 10 10 10 10 10  std::vector<int> bar (5,33);        // bar: 33 33 33 33 33  std::swap_ranges(foo.begin()+1, foo.end()-1, bar.begin());  // print out results of swap:  std::cout << "foo contains:";  for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  std::cout << "bar contains:";  for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

foo contains: 10 33 33 33 10bar contains: 10 10 10 33 33

(9)iter_swap

只交换两个序列中,两个迭代器所指向的一个值。

template <class ForwardIterator1, class ForwardIterator2>  void iter_swap (ForwardIterator1 a, ForwardIterator2 b);

代码示例:

int main () {  int myints[]={10,20,30,40,50 };              //   myints:  10  20  30  40  50  std::vector<int> myvector (4,99);            // myvector:  99  99  99  99  std::iter_swap(myints,myvector.begin());     //   myints: [99] 20  30  40  50                                                                                        // myvector: [10] 99  99  99  std::iter_swap(myints+3,myvector.begin()+2); //   myints:  99  20  30 [99] 50                                                                                                // myvector:  10  99 [40] 99  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

(10)transform

模板1:对 range [first1,last1)都执行op操作,然后复制给result。range [first1,last1)中的元素不会改变。

模板2:range [first1,last1)中的每个元素都和first2开始的元素,依次执行binary_op操作,然后复制给result。

//unary operation(1)template <class InputIterator, class OutputIterator, class UnaryOperation>  OutputIterator transform (InputIterator first1, InputIterator last1,                            OutputIterator result, UnaryOperation op);//binary operation(2)template <class InputIterator1, class InputIterator2,          class OutputIterator, class BinaryOperation>  OutputIterator transform (InputIterator1 first1, InputIterator1 last1,                            InputIterator2 first2, OutputIterator result,                            BinaryOperation binary_op);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::transform#include <vector>       // std::vector#include <functional>   // std::plusint op_increase (int i) { return ++i; }int main () {  std::vector<int> foo;  std::vector<int> bar;  // set some values:  for (int i=1; i<6; i++)    foo.push_back (i*10);                         // foo: 10 20 30 40 50  bar.resize(foo.size());                         // allocate space  std::transform (foo.begin(), foo.end(), bar.begin(), op_increase);                                                  // bar: 11 21 31 41 51  // std::plus adds together its two arguments:  std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());                                                  // foo: 21 41 61 81 101  std::cout << "foo contains:";  for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

(11)replace

对 range [first,last) 中所有的old_value元素,使用new_value替换。

template <class ForwardIterator, class T>  void replace (ForwardIterator first, ForwardIterator last,                const T& old_value, const T& new_value);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::replace#include <vector>       // std::vectorint main () {  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };  std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20  std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

myvector contains: 10 99 30 30 99 10 10 99

(12)replace_if

替换所有使得pred为真的元素。

template <class ForwardIterator, class UnaryPredicate, class T>  void replace_if (ForwardIterator first, ForwardIterator last,                   UnaryPredicate pred, const T& new_value );

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::replace_if#include <vector>       // std::vectorbool IsOdd (int i) { return ((i%2)==1); }int main () {  std::vector<int> myvector;  // set some values:  for (int i=1; i<10; i++) myvector.push_back(i);               // 1 2 3 4 5 6 7 8 9  std::replace_if (myvector.begin(), myvector.end(), IsOdd, 0); // 0 2 0 4 0 6 0 8 0  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

(13)replace_copy

从range [first,last) 拷贝元素到以result为起始的迭代器中, 并修改old_value为new_value。原来的序列元素保持不变。

template <class InputIterator, class OutputIterator, class T>  OutputIterator replace_copy (InputIterator first, InputIterator last,                               OutputIterator result,                               const T& old_value, const T& new_value);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::replace_copy#include <vector>       // std::vectorint main () {  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };  std::vector<int> myvector (8);  std::replace_copy (myints, myints+8, myvector.begin(), 20, 99);  for(auto x:myints)      std::cout<<x<<", ";  std::cout<<std::endl;  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

10, 20, 30, 30, 20, 10, 10, 20, myvector contains: 10 99 30 30 99 10 10 99

(14)replace_copy_if

从range [first,last) 拷贝元素到以result为起始的迭代器中, 如果满足pred为真,元素修改为new_value。原来的序列元素保持不变。

template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>  OutputIterator replace_copy_if (InputIterator first, InputIterator last,                                  OutputIterator result, UnaryPredicate pred,                                  const T& new_value);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::replace_copy_if#include <vector>       // std::vectorbool IsOdd (int i) { return ((i%2)==1); }int main () {  std::vector<int> foo,bar;  // set some values:  for (int i=1; i<10; i++) foo.push_back(i);          // 1 2 3 4 5 6 7 8 9  bar.resize(foo.size());   // allocate space  std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);                                                        // 0 2 0 4 0 6 0 8 0,只修改奇数  std::cout << "bar contains:";  for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

(15)fill

使用val填充 range [first,last)。

template <class ForwardIterator, class T>  void fill (ForwardIterator first, ForwardIterator last, const T& val);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::fill#include <vector>       // std::vectorint main () {  std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0  std::fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0  std::fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

myvector contains: 5 5 5 8 8 8 0 0

(16)fill_n

填充n个val元素到以first开始的序列

template <class OutputIterator, class Size, class T>  OutputIterator fill_n (OutputIterator first, Size n, const T& val);

(17)generate

以gen规则生成的元素,依次复制给 range [first,last)。

template <class ForwardIterator, class Generator>  void generate (ForwardIterator first, ForwardIterator last, Generator gen);

(18)generate_n

以gen规则生成的元素,依次复制给以first开始的n个元素。

template <class OutputIterator, class Size, class Generator>  OutputIterator generate_n (OutputIterator first, Size n, Generator gen);

(19)remove

删除 range [first,last)中和val相同的元素,并返回新序列的end迭代器。

template <class ForwardIterator, class T>  ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::removeint main () {  int myints[] = {10,20,30,30,20,10,10,20};      // 10 20 30 30 20 10 10 20  // bounds of range:  int* pbegin = myints;                          // ^  int* pend = myints+sizeof(myints)/sizeof(int); // ^                       ^  pend = std::remove (pbegin, pend, 20);         // 10 30 30 10 10 ?  ?  ?                                                 // ^              ^  std::cout << "range contains:";  for (int* p=pbegin; p!=pend; ++p)    std::cout << ' ' << *p;  std::cout << '\n';  return 0;}

输出:

range contains: 10 30 30 10 10

(20)remove_if

删除 range [first,last)中满足pred条件的元素,并返回新序列的end迭代器。

template <class ForwardIterator, class UnaryPredicate>  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,                             UnaryPredicate pred);

(21)remove_copy

除了和val相同的元素,复制range [first,last)中的元素到result开始的元素中。原来的序列保持不变。

template <class InputIterator, class OutputIterator, class T>  OutputIterator remove_copy (InputIterator first, InputIterator last,                              OutputIterator result, const T& val);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::remove_copy#include <vector>       // std::vectorint main () {  int myints[] = {10,20,30,30,20,10,10,20};               // 10 20 30 30 20 10 10 20  std::vector<int> myvector (8);  std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

(22)remove_copy_if

除了使得pred为真的元素,复制range [first,last)中的元素到result开始的元素中。原来的序列保持不变。

template <class InputIterator, class OutputIterator, class UnaryPredicate>  OutputIterator remove_copy_if (InputIterator first, InputIterator last,                                 OutputIterator result, UnaryPredicate pred);

(23)unique

在range[first,last)中,如果遇到连续的相同元素,只保留第一个。并返回处理完毕之后的end迭代器。

删除的地方补0,可以用resize去掉。

模板1:默认相等

模板2:自定义pred相等规则

//equality (1)template <class ForwardIterator>  ForwardIterator unique (ForwardIterator first, ForwardIterator last);//predicate (2)template <class ForwardIterator, class BinaryPredicate>  ForwardIterator unique (ForwardIterator first, ForwardIterator last,                          BinaryPredicate pred);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::unique, std::distance#include <vector>       // std::vectorbool myfunction (int i, int j) {  return (i==j);}int main () {  int myints[] = {10,20,20,20,30,30,20,20,10};           // 10 20 20 20 30 30 20 20 10  std::vector<int> myvector (myints,myints+9);  // using default comparison:  std::vector<int>::iterator it;  it = std::unique (myvector.begin(), myvector.end());   // 10 20 30 20 10 ?  ?  ?  ?,指向第一个?  myvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30 20 10  // using predicate comparison:  std::unique (myvector.begin(), myvector.end(), myfunction);   // (no changes)  // print out content:  std::cout << "myvector contains:";  for (it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

输出:

myvector contains: 10 20 30 20 10

(24)unique_copy

复制unique元素到result中,原来的元素保持不变。

//equality (1)template <class InputIterator, class OutputIterator>  OutputIterator unique_copy (InputIterator first, InputIterator last,                              OutputIterator result);//predicate (2)template <class InputIterator, class OutputIterator, class BinaryPredicate>  OutputIterator unique_copy (InputIterator first, InputIterator last,                              OutputIterator result, BinaryPredicate pred);

(25)reverse

反转序列

template <class BidirectionalIterator>  void reverse (BidirectionalIterator first, BidirectionalIterator last);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::reverse#include <vector>       // std::vectorint main () {  std::vector<int> myvector;  // set some values:  for (int i=1; i<10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9  std::reverse(myvector.begin(),myvector.end());    // 9 8 7 6 5 4 3 2 1  // 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;}

(26)reverse_copy

复制反转的序列,原来的序列保持不变。

template <class BidirectionalIterator, class OutputIterator>  OutputIterator reverse_copy (BidirectionalIterator first,                               BidirectionalIterator last, OutputIterator result);

(27)rotate

以middle为圆点,调换左右序列,其中middle迭代器指向的元素为第一个元素。。

template <class ForwardIterator>  ForwardIterator rotate (ForwardIterator first, ForwardIterator middle,                          ForwardIterator last);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::rotate#include <vector>       // std::vectorint main () {  std::vector<int> myvector;  // set some values:  for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9  std::rotate(myvector.begin(),myvector.begin()+3,myvector.end());                                                  // 4 5 6 7 8 9 1 2 3  // 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;}

输出:

myvector contains: 4 5 6 7 8 9 1 2 3

(28)rotate_copy

复制旋转过的元素到result中,但是原来的序列保持不变。这一点像reverse_copy。

template <class ForwardIterator, class OutputIterator>  OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle,                              ForwardIterator last, OutputIterator result);

(29)random_shuffle

shuffle意思是洗牌。

gen是自己定义的随机种子。

//generator by default (1)template <class RandomAccessIterator>  void random_shuffle (RandomAccessIterator first, RandomAccessIterator last);//specific generator (2)template <class RandomAccessIterator, class RandomNumberGenerator>  void random_shuffle (RandomAccessIterator first, RandomAccessIterator last,                       RandomNumberGenerator&& gen);

(30)shuffle

也是重新洗牌。

template <class RandomAccessIterator, class URNG>  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);

3. 划分操作(Partitions)

(1)is_partitioned

(2)partition

(3)stable_partition

(4)partition_copy

(5)partition_point

4. 排序操作(sorting)

(1)sort

默认排序:升序模板2:根据comp返回true的状态排序

不保证相同元素,保持原来的排序方法。如果需要保持原来的顺序,可以使用stable_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);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::sort#include <vector>       // std::vectorbool 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;}

(2)stable_sort

和sort一样,只不过相同元素保持原来的排序。

(3)partial_sort

middle之前的元素,都是小于或等于middle,而且经过排序。middle之后的元素没有指定顺序。

//default (1)template <class RandomAccessIterator>  void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,                     RandomAccessIterator last);//custom (2)template <class RandomAccessIterator, class Compare>  void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,                     RandomAccessIterator last, Compare comp);

(4)partial_sort_copy

从range [first,last),复制最小的一部分元素,到 [result_first,result_last),并排序。原来的序列保持不变。

[first,last)小于[result_first,result_last)则只截取最小的一部分,否则全部排序并复制。

模板1:默认升排序

模板2:自定义comp规则。

//default (1)template <class InputIterator, class RandomAccessIterator>  RandomAccessIterator    partial_sort_copy (InputIterator first,InputIterator last,                       RandomAccessIterator result_first,                       RandomAccessIterator result_last);//custom (2)template <class InputIterator, class RandomAccessIterator, class Compare>  RandomAccessIterator    partial_sort_copy (InputIterator first,InputIterator last,                       RandomAccessIterator result_first,                       RandomAccessIterator result_last, Compare comp);

(5)is_sorted

判断序列是否排序。

模板1:默认排序

模板2:自定义comp规则。

//default (1)template <class ForwardIterator>  bool is_sorted (ForwardIterator first, ForwardIterator last);//custom (2)template <class ForwardIterator, class Compare>  bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);

(6)is_sorted_until

模板1:返回第一个不满足默认升排序的迭代器

模板2:返回第一个不满足自定义comp规则的迭代器。

//default (1)template <class ForwardIterator>  ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last);//custom (2)template <class ForwardIterator, class Compare>  ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last,                                   Compare comp);

(7)nth_element

重新排列range [first,last)元素。nth左边的元素是小的,右边的元素是大的。

模板1:默认排序。

模板2:comp规则

//default (1)template <class RandomAccessIterator>  void nth_element (RandomAccessIterator first, RandomAccessIterator nth,                    RandomAccessIterator last);//custom (2)template <class RandomAccessIterator, class Compare>  void nth_element (RandomAccessIterator first, RandomAccessIterator nth,                    RandomAccessIterator last, Compare comp);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::nth_element, std::random_shuffle#include <vector>       // std::vectorbool myfunction (int i,int j) { return (i<j); }int main () {  std::vector<int> myvector;  // set some values:`在这里插入代码片`  for (int i=1; i<10; i++) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9  std::random_shuffle (myvector.begin(), myvector.end());//洗牌  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  // using default comparison (operator <):  //以myvector.begin()+5为中心  std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end());  // using function as comp  std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end(),myfunction);  // 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;}

输出:

myvector contains: 5 4 8 9 1 6 3 2 7myvector contains: 5 2 3 1 4 6 7 8 9

5. 二分查找操作(Binary search)

二分查找需要所有元素经过排序。

(1)lower_bound

模板1:返回第一个不小于val元素指向的迭代器。

模板2:依据comp规则,返回第一个不小于val的元素的迭代器。

模板1内所有元素都是通过”<“排序,模板2都是通过comp排序。

//default (1)template <class ForwardIterator, class T>  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,                               const T& val);//custom (2)template <class ForwardIterator, class T, class Compare>  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,                               const T& val, Compare comp);
#include <iostream>     // std::cout#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort#include <vector>       // std::vectorint main () {  int myints[] = {10,20,30,30,20,10,10,20};  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20  std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30  std::vector<int>::iterator low,up;  low=std::lower_bound (v.begin(), v.end(), 20); // 指向第一个20  up= std::upper_bound (v.begin(), v.end(), 20); // 指向20后面第一个大于20的元素  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';  return 0;}

输出:

lower_bound at position 3upper_bound at position 6

(2)upper_bound

模板1:返回第一个大于val元素指向的迭代器

模板2:依据comp规则,返回第一个大于val的元素的迭代器。

模板1内所有元素都是通过”<“排序,模板2都是通过comp排序。

//default (1)template <class ForwardIterator, class T>  ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,                               const T& val);//custom (2)template <class ForwardIterator, class T, class Compare>  ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,                               const T& val, Compare comp);

(3)equal_range

模板1:返回 range [first,last)内,所有等于val元素的边界对pair(low, upper)。

模板2:返回 range [first,last)内,所有等于val元素的边界对pair(low, upper)。

模板1内所有元素都是通过”<“排序,模板2都是通过comp排序。

//default (1)template <class ForwardIterator, class T>  pair<ForwardIterator,ForwardIterator>    equal_range (ForwardIterator first, ForwardIterator last, const T& val);//custom (2)template <class ForwardIterator, class T, class Compare>  pair<ForwardIterator,ForwardIterator>    equal_range (ForwardIterator first, ForwardIterator last, const T& val,                  Compare comp);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::equal_range, std::sort#include <vector>       // std::vectorbool mygreater (int i,int j) { return (i>j); }int main () {  int myints[] = {10,20,30,30,20,10,10,20};  std::vector<int> v(myints,myints+8);                         // 10 20 30 30 20 10 10 20  std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;  // using default comparison:  std::sort (v.begin(), v.end());                                  // 10 10 10 20 20 20 30 30  bounds=std::equal_range (v.begin(), v.end(), 20);//          ^                ^  // using "mygreater" as comp:  std::sort (v.begin(), v.end(), mygreater);                                       // 30 30 20 20 20 10 10 10  bounds=std::equal_range (v.begin(), v.end(), 20, mygreater); //       ^                 ^  std::cout << "bounds at positions " << (bounds.first - v.begin());  std::cout << " and " << (bounds.second - v.begin()) << '\n';  return 0;}

输出:

bounds at positions 2 and 5

(4)binary_search

range [first,last)中的元素至少有一个等于val,则返回true,否则返回false。

序列应该按照默认升序或者comp规则排序。

//default (1)template <class ForwardIterator, class T>  bool binary_search (ForwardIterator first, ForwardIterator last,                      const T& val);//custom (2)template <class ForwardIterator, class T, class Compare>  bool binary_search (ForwardIterator first, ForwardIterator last,                      const T& val, Compare comp);

6. 集合(Merge)

(1)merge

(2)inplace_merge

(3)includes

(4)set_union

(5)set_intersection

(6)set_difference

(7)set_symmetric_difference

7. 堆操作

(1)push_heap

(2)pop_heap

(3)make_heap

(4)sort_heap

(5)is_heap

(6)is_heap_until

8. 最小最大值操作

(1)min

返回两个元素的最小的一个。

模板1:内置数据类型

模板2和模板3:自己定义comp

模板3可以有多个元素。

//default (1)template <class T> constexpr const T& min (const T& a, const T& b);//custom (2)template <class T, class Compare>  constexpr const T& min (const T& a, const T& b, Compare comp);//initializer list (3)template <class T> constexpr T min (initializer_list<T> il);template <class T, class Compare>  constexpr T min (initializer_list<T> il, Compare comp);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::minint main () {  std::cout << "min(1,2)==" << std::min(1,2) << '\n';  std::cout << "min(2,1)==" << std::min(2,1) << '\n';  std::cout << "min('a','z')==" << std::min('a','z') << '\n';  std::cout << "min(3.14,2.72)==" << std::min(3.14,2.72) << '\n'; std::cout<<std::min({1,2,4,5,6,7})<<std::endl;  return 0;}

输出:

min(1,2)==1min(2,1)==1min(‘a’,’z’)==amin(3.14,2.72)==2.721

(2)max

同min

(3)minmax

返回make_pair(a,b),a为最小值,b为最大值。

模板3可以有多个元素。

//default (1)template <class T>  constexpr pair <const T&,const T&> minmax (const T& a, const T& b);//custom (2)template <class T, class Compare>  constexpr pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp);//initializer list (3)template <class T>  constexpr pair<T,T> minmax (initializer_list<T> il);template <class T, class Compare>  constexpr pair<T,T> minmax (initializer_list<T> il, Compare comp);

(4)min_element

模板1:返回最小元素的迭代器

模板2:根据comp的小于号定义规则(一定要升序),不然结果相反。

//default (1)template <class ForwardIterator>  ForwardIterator min_element (ForwardIterator first, ForwardIterator last);//custom (2)template <class ForwardIterator, class Compare>  ForwardIterator min_element (ForwardIterator first, ForwardIterator last,                               Compare comp);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::min_element, std::max_elementbool myfn(int i, int j) { return i<j; }struct myclass {  bool operator() (int i,int j) { return i<j; }} myobj;int main () {  int myints[] = {3,7,2,5,6,4,9};  // using default comparison:  std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';  std::cout << "The largest element is "  << *std::max_element(myints,myints+7) << '\n';  // using function myfn as comp:  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myfn) << '\n';  // using object myobj as comp:  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myobj) << '\n';  return 0;}

输出:

The smallest element is 2The largest element is 9The smallest element is 2The largest element is 9The smallest element is 2The largest element is 9

(5)max_element

同min_element

(6)minmax_element

同minmax规则,不过返回的是迭代器。

9. 其他

(1)lexicographical_compare

类似于字符串比较大小,这里可以自定义数据类型比较。[first1,last1) 的元素小于[first2,last2),则返回true。

模板1:默认小于

模板2:自定义comp判断。

//default (1)template <class InputIterator1, class InputIterator2>  bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,                                InputIterator2 first2, InputIterator2 last2);//custom (2)template <class InputIterator1, class InputIterator2, class Compare>  bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,                                InputIterator2 first2, InputIterator2 last2,                                Compare comp);

代码示例:

#include <iostream>     // std::cout, std::boolalpha#include <algorithm>    // std::lexicographical_compare#include <cctype>       // std::tolower// a case-insensitive comparison function:bool mycomp (char c1, char c2){ return std::tolower(c1)<std::tolower(c2); }//自定义,转换成小写比较int main () {  char foo[]="Apple";  char bar[]="apartment";  std::cout << std::boolalpha;  std::cout << "Comparing foo and bar lexicographically (foo<bar):\n";  std::cout << "Using default comparison (operator<): ";  std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9);  std::cout << '\n';  std::cout << "Using mycomp as comparison object: ";  std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9,mycomp);  std::cout << '\n';  return 0;}

输出:

Comparing foo and bar lexicographically (foo<bar):Using default comparison (operator<): trueUsing mycomp as comparison object: false

(2)next_permutation

permutation表示排序。 获取比现在的数据排列大的一组数据,并获取新的排列。比如比1,2,3大的下一次排列为1,3,2. 如果已经是最大排序,那么它先获取下一次的排序,比如321下一次的排序为123,并返回false。

模板1:默认排序

模板2:自定义comp排序

//default (1)template <class BidirectionalIterator>  bool next_permutation (BidirectionalIterator first,                         BidirectionalIterator last);//custom (2)template <class BidirectionalIterator, class Compare>  bool next_permutation (BidirectionalIterator first,                         BidirectionalIterator last, Compare comp);

代码示例:

#include <iostream>     // std::cout#include <algorithm>    // std::next_permutation, std::sortint main () {  int myints[] = {1,2,3};  std::sort (myints,myints+3);  std::cout << "The 3! possible permutations with 3 elements:\n";  do {    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';  } while ( std::next_permutation(myints,myints+3) );  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';  return 0;}

输出结果:

The 3! possible permutations with 3 elements:1 2 31 3 22 1 32 3 13 1 23 2 1After loop: 1 2 3

(3)prev_permutation

用法同next_permutation,只不过它获取的是下一次的较大值。


参考:http://www.cplusplus.com/reference/algorithm/

到此这篇关于C++头文件algorithm中的函数功能详解的文章就介绍到这了,更多相关C++头文件algorithm函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

饶人不是痴汉,痴汉不会饶人。

C++头文件algorithm中的函数功能详解

相关文章:

你感兴趣的文章:

标签云: