Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ algorithm library

C++ algorithm library

The C++ standard library's header provides a set of algorithms for operating on containers (such as arrays, vectors, lists, etc.). These algorithms include sorting, searching, copying, comparing, and so on; they are important tools for writing efficient, reusable code.

The header defines a set of template functions that can be applied to any type of container, as long as the container supports iterators. These algorithms usually take two or more iterators as parameters, representing the start and end positions of the operation.

Syntax

Most functions follow the basic syntax below:

algorithm_name(container.begin(), container.end(), ...);

Here, container is a container object,begin() and end() is a member function of the container that returns iterators pointing to the beginning and end of the container.

Example

1. Sorting algorithms

Function: sort

Definition: Sorts the elements in a container.

Syntax:


sort(container.begin(), container.end(), compare_function);

where compare_function is an optional comparison function used to customize the sorting order.

Example

#include

#include

#include

int

main

(

)

{

    std

::

vector

<
int
numbers
=
{
5
,
2
,
9
,
1
,
5
,
6
}

;

    std

::

sort

(

numbers.

begin

(

)

, numbers.

end

(

)

)

;

   

for

(

int

num

:

numbers

)

{

        std

::

cout

<<

num

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Output result:


1 2 5 5 6 9 

std::partial_sort: Sorts a partial range; the first n elements are ordered.


std::partial_sort(vec.begin(), vec.begin() + 3, vec.end());

std::stable_sort: Stable sort that preserves the relative order of equal elements.


std::stable_sort(vec.begin(), vec.end());

2. Searching algorithms

Function: find

Definition: Finds the first element in a container that matches a given value.

Syntax:


auto it = find(container.begin(), container.end(), value);

If found, it points to the matching element; if not found, it equals container.end().

Example

#include

#include

#include

int

main

(

)

{

    std

::

vector

<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
}

;

   

auto

it

=

std

::

find

(

numbers.

begin

(

)

, numbers.

end

(

)

,

3

)

;

   

if

(

it

!

=

numbers.

end

(

)

)

{

        std

::

cout

<<

"Found: "

<<

it

<<

std

::

endl

;

   

}

else

{

        std

::

cout

<<

"Value not found."

<<

std

::

endl

;

   

}

   

return

0

;

}

Output result:


Found: 3

std::binary_search: Performs binary search on a sorted range.

std::sort(vec.begin(), vec.end());  // 先排序
bool found = std::binary_search(vec.begin(), vec.end(), 4);

std::find_if: Finds the first element that satisfies a specific condition.


auto it = std::find_if(vec.begin(), vec.end(), [](int x) { return x > 3; });

3. Copying algorithms

Function: copy

Definition: Copies elements from one range to another container or array.

Syntax:


copy(source_begin, source_end, destination_begin);

Example:

Example

#include

#include

#include

int

main

(

)

{

    std

::

vector

<
int
source
=
{
1
,
2
,
3
,
4
,
5
}

;

   

int

destination

[

5

]

;

    std

::

copy

(

source.

begin

(

)

, source.

end

(

)

, destination

)

;

   

for

(

int

i

=

0

;

i

<

5

;

++

i

)

{

        std

::

cout

<<

destination

[

i

]

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Output result:


1 2 3 4 5 

4. Comparison algorithms

Function: equal

Definition: Compares whether the elements of two containers or two ranges are equal.

Syntax:


bool result = equal(first1, last1, first2);

或

bool result = equal(first1, last1, first2, compare_function);

Example

#include

#include

#include

int

main

(

)

{

    std

::

vector

<
int
v1
=
{
1
,
2
,
3
,
4
,
5
}

;

    std

::

vector

<
int
v2
=
{
1
,
2
,
3
,
4
,
5
}

;

   

bool

are_equal

=

std

::

equal

(

v1.

begin

(

)

, v1.

end

(

)

, v2.

begin

(

)

)

;

    std

::

cout

<<

(

are_equal

?

"Vectors are equal."

:

"Vectors are not equal."

)

<<

std

::

endl

;

   

return

0

;

}

Output result:


Vectors are equal.

5. Modifying algorithms

std::reverse: Reverses the order of elements in a range.


std::reverse(vec.begin(), vec.end());

std::fill: Assigns a given value to all elements in a specified range.


std::fill(vec.begin(), vec.end(), 0);  // 所有元素设为 0

std::replace: Replaces a value within a range with another value.


std::replace(vec.begin(), vec.end(), 1, 99);  // 将所有 1 替换为 99

std::copy: Copies elements within a range to another range.


std::vector vec2(6);
std::copy(vec.begin(), vec.end(), vec2.begin());

6. Permutation algorithms

std::next_permutation: Generates the next lexicographical permutation; returns false if no next permutation exists.

std::vector vec = {1, 2, 3};
do {
    for (int n : vec) std::cout << n << " ";
    std::cout << std::endl;
} while (std::next_permutation(vec.begin(), vec.end()));

std::prev_permutation: Generates the previous lexicographical permutation.


std::prev_permutation(vec.begin(), vec.end());

7. Merging algorithms

std::merge: Merges two sorted ranges into one sorted range.


std::vector vec1 = {1, 3, 5};
std::vector vec2 = {2, 4, 6};
std::vector result(6);
std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin());

std::inplace_merge: Merges two sorted subranges within a single range.


std::inplace_merge(vec.begin(), middle, vec.end());

8. Set algorithms

std::set_union: Computes the union of two sorted sets.


std::vector result(10);
auto it = std::set_union(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin());
result.resize(it - result.begin());

std::set_intersection: Computes the intersection of two sorted sets.


auto it = std::set_intersection(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin());
result.resize(it - result.begin());

std::set_difference: Computes the difference of two sets.


auto it = std::set_difference(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin());
result.resize(it - result.begin());

9. Other useful algorithms

std::accumulate (requires the library): Computes the cumulative sum of elements in a range.


#include 
int sum = std::accumulate(vec.begin(), vec.end(), 0);

std::for_each: Performs an operation on each element in a range.


std::for_each(vec.begin(), vec.end(), [](int& x) { x += 1; });

std::min_element and std::max_element: Find the minimum and maximum values in a range.


auto min_it = std::min_element(vec.begin(), vec.end());
auto max_it = std::max_element(vec.begin(), vec.end());

is a very powerful tool in the C++ standard library; it provides a large number of generic algorithms that can greatly simplify programming