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

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

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

### （1）all_of

```template
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);```

```#include      // std::cout
#include     // std::all_of
#include

int main () {
//std::array foo = {3,5,7,11,13,17,19,23};
std::list 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

```template
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);```

### （3）none_of

```template
bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred);```

（4）for_each

• fn可以是普通函数也可以是仿函数(函数对象)。
• fn后面不可以添加括号
```template
Function for_each (InputIterator first, InputIterator last, Function fn);```

```#include      // std::cout
#include     // std::for_each
#include        // std::vector

void myfunction (int i) {  // function:普通函数
std::cout << ' ' << i;
}

struct myclass {           // function object type:，仿函数，或者函数对象
void operator() (int i) {std::cout << ' ' << i;}
} myobject;

int main () {
std::vector 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

```template
InputIterator find (InputIterator first, InputIterator last, const T& val);```

```#include      // std::cout
#include     // std::find
#include        // std::vector

int 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

// using std::find with vector and iterator:
std::vector myvector (myints,myints+4);
std::vector::iterator it;

it = find (myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
std::cout << "Element found in myvector: " << *it << '\n';
else

return 0;
}```

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

### （6）find_if

```template
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);```

```#include      // std::cout
#include     // std::find_if
#include        // std::vector

bool IsOdd (int i) {
return ((i%2)==1);
}

int main () {
std::vector myvector;

myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);

std::vector::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

```template
InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred);```

```#include      // std::cout
#include     // std::find_if_not
#include         // std::array

int main () {
std::array foo = {1,2,3,4,5};

std::array::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

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

```#include      // std::cout
#include     // std::find_end
#include        // std::vector

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

int main () {
int myints[] = {1,2,3,4,5,1,2,3,4,5};
std::vector haystack (myints,myints+10);

int needle1[] = {1,2,3};

// using default comparison:
std::vector::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 5
needle2 last found at position 3

（9）find_first_of

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

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

```#include      // std::cout
#include        // std::vector

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

int main () {
int myints[] = {5,20,5,30,30,20,10,10,20};
std::vector myvector (myints,myints+8);
std::vector::iterator it;

// using default comparison:

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: 30
the second pair of repeated elements are: 10

（11）count

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

```#include      // std::cout
#include     // std::count
#include        // std::vector

int 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 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

```template
typename iterator_traits::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);```

```#include      // std::cout
#include     // std::count_if
#include        // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
std::vector 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

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

```#include      // std::cout
#include     // std::mismatch
#include        // std::vector
#include       // std::pair

bool mypredicate (int i, int j) {
return (i==j);
}

int main () {
std::vector 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::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 80
Second mismatching elements: 40 and 320

（14）equal

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

```#include      // std::cout
#include     // std::equal
#include        // std::vector

bool mypredicate (int i, int j) {
return (i==j);
}

int main () {
int myints[] = {20,40,60,80,100};               //   myints: 20 40 60 80 100
std::vectormyvector (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
bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2);
//predicate (2)
template
bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, BinaryPredicate pred);```

```#include      // std::cout
#include     // std::is_permutation
#include         // std::array

int main () {
std::array foo = {1,2,3,4,5};
std::array 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

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

```#include      // std::cout
#include     // std::search
#include        // std::vector

bool mypredicate (int i, int j) {
return (i==j);
}

int main () {
std::vector 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::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

// 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

return 0;
}```

needle1 found at position 3

（17）search_n

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

## 2. 修改内容的序列操作

### （1）copy

```template
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);```

```#include      // std::cout
#include     // std::copy
#include        // std::vector

int main () {
int myints[]={10,20,30,40,50,60,70};
std::vector myvector (7);

std::copy ( myints, myints+7, myvector.begin() );

std::cout << "myvector contains:";
for (std::vector::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

```template
OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);```

### （3）copy_if

```template
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);```

### （4）copy_backward

```template
BidirectionalIterator2 copy_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);```

```#include      // std::cout
#include     // std::copy_backward
#include        // std::vector

int main () {
std::vector 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::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

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

```template
OutputIterator move (InputIterator first, InputIterator last, OutputIterator result);```

```#include      // std::cout
#include     // std::move (ranges)
#include       // std::move (objects)
#include        // std::vector
#include        // std::string

int main () {
std::vector foo = {"air","water","fire","earth"};
std::vector 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

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

```template
BidirectionalIterator2 move_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);```

```#include      // std::cout
#include     // std::move_backward
#include        // std::string

int 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已经把该函数移到头文件中，已经不在中。

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

```#include      // std::cout
#include     // std::swap
#include        // std::vector

int main () {
int x=10, y=20;                              // x:10 y:20
std::cout<<"x add: "<<&x << "y add: "<< &y< 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::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

std::cout << "bar contains:";
for (std::vector::iterator it=bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

foo contains: 10 10 10 10 10 10
bar contains: 20 20 20 20

### （8）swap_ranges

```template
ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2);```

```#include      // std::cout
#include     // std::swap_ranges
#include        // std::vector

int main () {
std::vector foo (5,10);        // foo: 10 10 10 10 10
std::vector 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::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

std::cout << "bar contains:";
for (std::vector::iterator it=bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

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

### （9）iter_swap

```template
void iter_swap (ForwardIterator1 a, ForwardIterator2 b);```

```int main () {

int myints[]={10,20,30,40,50 };              //   myints:  10  20  30  40  50
std::vector 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::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

### （10）transform

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

```#include      // std::cout
#include     // std::transform
#include        // std::vector
#include    // std::plus

int op_increase (int i) { return ++i; }

int main () {
std::vector foo;
std::vector 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());
// foo: 21 41 61 81 101

std::cout << "foo contains:";
for (std::vector::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

### （11）replace

```template
void replace (ForwardIterator first, ForwardIterator last,
const T& old_value, const T& new_value);```

```#include      // std::cout
#include     // std::replace
#include        // std::vector

int main () {
int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
std::vector 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::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

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

```#include      // std::cout
#include     // std::replace_if
#include        // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
std::vector 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::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

### （13）replace_copy

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

```#include      // std::cout
#include     // std::replace_copy
#include        // std::vector

int main () {
int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };

std::vector myvector (8);
std::replace_copy (myints, myints+8, myvector.begin(), 20, 99);

for(auto x:myints)
std::cout<::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

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

```#include      // std::cout
#include     // std::replace_copy_if
#include        // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
std::vector 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::iterator it=bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

### （15）fill

```template
void fill (ForwardIterator first, ForwardIterator last, const T& val);```

```#include      // std::cout
#include     // std::fill
#include        // std::vector

int main () {
std::vector 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::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

```template
OutputIterator fill_n (OutputIterator first, Size n, const T& val);```

（17）generate

```template
void generate (ForwardIterator first, ForwardIterator last, Generator gen);```

（18）generate_n

```template
OutputIterator generate_n (OutputIterator first, Size n, Generator gen);```

（19）remove

```template
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);```

```#include      // std::cout
#include     // std::remove

int 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

```template
ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
UnaryPredicate pred);```

（21）remove_copy

```template
OutputIterator remove_copy (InputIterator first, InputIterator last,
OutputIterator result, const T& val);```

```#include      // std::cout
#include     // std::remove_copy
#include        // std::vector

int main () {
int myints[] = {10,20,30,30,20,10,10,20};               // 10 20 30 30 20 10 10 20
std::vector 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::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

（22）remove_copy_if

```template
OutputIterator remove_copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);```

（23）unique

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

```#include      // std::cout
#include     // std::unique, std::distance
#include        // std::vector

bool 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 myvector (myints,myints+9);

// using default comparison:
std::vector::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

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

（25）reverse

```template
void reverse (BidirectionalIterator first, BidirectionalIterator last);```

```#include      // std::cout
#include     // std::reverse
#include        // std::vector

int main () {
std::vector 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::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

（26）reverse_copy

```template
OutputIterator reverse_copy (BidirectionalIterator first,
BidirectionalIterator last, OutputIterator result);```

（27）rotate

```template
ForwardIterator rotate (ForwardIterator first, ForwardIterator middle,
ForwardIterator last);```

```#include      // std::cout
#include     // std::rotate
#include        // std::vector

int main () {
std::vector 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::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

```template
OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle,
ForwardIterator last, OutputIterator result);```

（29）random_shuffle

shuffle意思是洗牌。

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

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

（30）shuffle

```template
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

```//default (1)
template
void sort (RandomAccessIterator first, RandomAccessIterator last);
//custom (2)
template
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);```

```#include      // std::cout
#include     // std::sort
#include        // std::vector

bool myfunction (int i,int j) { return (i 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::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}```

（2）stable_sort

（3）partial_sort

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

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

（4）partial_sort_copy

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

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

（5）is_sorted

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

（6）is_sorted_until

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

（7）nth_element

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

```#include      // std::cout
#include     // std::nth_element, std::random_shuffle
#include        // std::vector

bool myfunction (int i,int j) { return (i 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::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::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 7
myvector contains: 5 2 3 1 4 6 7 8 9

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

（1）lower_bound

```//default (1)
template
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
const T& val);
//custom (2)
template
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);```
```#include      // std::cout
#include     // std::lower_bound, std::upper_bound, std::sort
#include        // std::vector

int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector 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::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 3
upper_bound at position 6

（2）upper_bound

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

（3）equal_range

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

```#include      // std::cout
#include     // std::equal_range, std::sort
#include        // std::vector

bool mygreater (int i,int j) { return (i>j); }

int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector v(myints,myints+8);                         // 10 20 30 30 20 10 10 20
std::pair::iterator,std::vector::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。

```//default (1)
template
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
//custom (2)
template
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

（1）push_heap

（2）pop_heap

（3）make_heap

（4）sort_heap

（5）is_heap

（6）is_heap_until

## 8. 最小最大值操作

（1）min

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

```#include      // std::cout
#include     // std::min

int 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<
```

min(1,2)==1
min(2,1)==1
min('a','z')==a
min(3.14,2.72)==2.72
1

（2）max

（3）minmax

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

（4）min_element

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

```#include      // std::cout
#include     // std::min_element, std::max_element

bool myfn(int i, int j) { return i
```

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

（5）max_element

（6）minmax_element

## 9. 其他

（1）lexicographical_compare

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

```#include      // std::cout, std::boolalpha
#include     // std::lexicographical_compare
#include        // std::tolower

// a case-insensitive comparison function:
bool mycomp (char c1, char c2)
{ return std::tolower(c1)
```

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

（2）next_permutation

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

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

```#include      // std::cout
#include     // std::next_permutation, std::sort

int 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 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3

（3）prev_permutation