Explore STL algorithms and explore stl

Source: Internet
Author: User
Tags intl

Explore STL algorithms and explore stl
Algorithm

 

 

The STL algorithm consists of header files <algorithm>, <numeric>, and <functional>. To use algorithm functions in STL, the header file <algorithm> must be included. For numeric algorithms, <numeric> and <functional> define some template classes to declare function objects.

 

Category

 

Algorithms in STL are roughly divided into four types:
1. Non-Variable Sequence Algorithm: an algorithm that does not directly modify the container content it operates on.
2. Variable Sequence Algorithm: an algorithm that allows you to modify the container content that they operate on.
3. Sorting Algorithm: Includes sorting and merging algorithms, search algorithms, and set operations on ordered sequences.
4. numeric algorithm: computes the container content.

 

 

All algorithms are classified in detail and the functions are described as follows:

 

 

Algorithm Introduction

 

Search Algorithm


<1> Search Algorithm (13): determines whether a container contains a value.


Adjacent_find: within the scope of the iterator pair of identification elements, find a pair of adjacent repeated elements, and return

ForwardIterator. Otherwise, return last. The overloaded version uses the input binary operator instead of the equal judgment.

Binary_search: searches for the value in the ordered sequence, and returns true if it finds it. The overloaded version is used to determine the specified comparison function object or function pointer.

Equal.


Count: Use the equal operator to compare the elements in the flag range with the input value and return the number of equal elements.
Count_if: uses the input operator to operate the elements in the flag range and returns the number of true results.


Performance_range: The function is similar to equal. A pair of iterator is returned. The first one indicates lower_bound, and the second one indicates upper_bound.

Find: Compares the elements in the specified range with the input values using the equals operator of the underlying elements. When the match ends, an InputIterator of the element is returned.
Find_end: finds the last occurrence of "second sequence of the input pair of iterator signs" within the specified range. If it is found, the first ForwardIterator of the last pair is returned. Otherwise, the first ForwardIterator of the input "other pair" is returned. The overload version uses the operator entered by the user to replace the equals operation.
Find_first_of: searches for the first appearance of any element in the second sequence of the input pair of iterator signs within the specified range. The overload version uses User-Defined operators.
Find_if: Use the input function instead of the equals operator to execute find.

Lower_bound: returns a ForwardIterator, pointing to the first position in the range of ordered sequences where a specified value can be inserted without disrupting the container sequence. Reload functions use custom comparison operations.
Upper_bound: returns a ForwardIterator that points to the last position where values are inserted within the range of the ordered sequence without disrupting the container sequence. This position indicates a value greater than the value. Reload functions use custom comparison operations.
Search: returns a ForwardIterator in two ranges. The query is successful and points to the position where the subsequence (the second range) appears for the first time in the first range. If the search fails, it points to last1. Reload versions use custom comparison operations.


Search_n: searches for the sub-sequence of val occurrence n times within the specified range. Reload versions use custom comparison operations.

 

 

 

Sorting and General Algorithms

 

<2> sorting and general algorithms (14): provides element sorting policies.


Inplace_merge: merges two ordered sequences, and the result sequence covers the range of the two ends. Reload versions are sorted by input operations.
Merge: merges two ordered sequences and stores them in another sequence. Reload versions use custom comparisons.


Nth_element: sorts the sequences in the range, so that all elements smaller than the nth element appear before it, and those greater than it appear behind it. Reload versions use custom comparison operations.


Partial_sort: Partially sorts the sequence. The number of elements to be sorted can be placed within the range. Reload versions use custom comparison operations.
Partial_sort_copy: similar to partial_sort, but the sorted sequence is copied to another container.
Partition: sorts elements in a specified range. Use the input function to place the elements whose result is true before the elements whose result is false.


Random_shuffle: Randomly adjusts the order of elements in the specified range. Input a random number to generate a random number for the overloaded version.


Reverse: sorts elements in a specified range in reverse order.
Reverse_copy: similar to reverse, but writes the result to another container.


Rotate: Move the element within the specified range to the end of the container. The element pointed to by middle becomes the first element of the container.
Rotate_copy: similar to rotate, but writes the result to another container.


Sort: sorts the elements in the specified range in ascending order. Reload versions use custom comparison operations.

Stable_sort: similar to sort, but retains the sequential relationship between equal elements.
Stable_partition: similar to partition, but the relative sequence in the container is not guaranteed.

 

 

Delete and replace Algorithms

 

<3> Delete and replace algorithms (15)
Copy: copy Sequence
Copy_backward: similar to copy, but the elements are copied in reverse order.


Iter_swap: Exchange two ForwardIterator values.


Remove: deletes all elements in the specified range that are equal to the specified element. Note that this function is not actually deleted. Built-in functions are not suitable for removing and remove_if functions.
Remove_copy: Copies all unmatched elements to a specific container and returns OutputIterator to the next position of the last element to be copied.
Remove_if: delete all elements whose input results are true within the specified range.
Remove_copy_if: Copies all unmatched elements to a specified container.


Replace: replace all elements in the specified range with vnew.
Replace_copy: similar to replace, but writes the result to another container.
Replace_if: replace all elements whose operation results are true within the specified range with a new value.
Replace_copy_if: replace_if, but write the result to another container.


Swap: swap the values stored in two objects.
Swap_range: swap the elements in the specified range with the values of the elements in another sequence.


Unique: removes duplicate elements in a sequence. Similar to removing, it cannot actually Delete elements. Reload versions use custom comparison operations.
Unique_copy: similar to unique, but outputs the result to another container.

 

 

Permutation and combination algorithms

 

<4> permutation and combination algorithms (2): provides the ability to compute all possible permutation and combination of a given set in a certain order.


Next_permutation: retrieves the sorting within the current range and sorts it again to the next one. Reload versions use custom comparison operations.
Prev_permutation: extracts the sequence within the specified range and sorts it back to the previous sequence. If the previous sequence does not exist, false is returned. Reload versions use custom comparison operations.

 

 

Arithmetic Algorithms

 

 

<5> arithmetic algorithms (4)


Accumulate: The sum of the sequence segment elements of the identifier added to an initial value specified by val. The overloaded version is no longer used for addition, but the binary operators passed in are applied to elements.
Partial_sum: Creates a new sequence. Each element value indicates the sum of all elements before the position in the specified range. The overloaded version uses custom operations instead of addition.
Inner_product: Perform Inner Product (the corresponding element is multiplied and then summed) on the two sequences and add inner product to the initial value of an input. The overloaded version uses user-defined operations.
Adjacent_difference: Creates a new sequence. Each new value in the new sequence represents the difference between the current element and the previous element. The overloaded version uses the specified binary operation to calculate the difference between adjacent elements.

 

 

Generation and variant Algorithms

 

<6> generation and variant algorithms (6)


Fill: assigns the input value to all elements in the flag range.
Fill_n: assigns the input value to all elements in the first + n range.
For_each: Performs iterative access to all elements in the specified range using the specified function in sequence, and returns the specified function type. This function cannot modify the elements in the sequence.


Generate: continuously call the input function to fill the specified range.
The generate_n: generate function is similar to that of filling n elements starting with the specified iterator.
Transform: applies the input operation to each element in the specified range and generates a new sequence. The overloaded version applies the operation to one element, and the other element comes from another input sequence. The result is output to the specified container.

 

 

 

Relational Algorithms

 

<7> relational algorithms (8)


Equal: returns true if the two sequences have equal elements in the flag range. The overloaded version uses the input operator instead of the default equal operator.

Des: determines whether all elements in the first specified range are included in the second range. If true is returned successfully, the <operator of the underlying element is used. The overload version uses the user-input function.


Lexicographical_compare: Compares two sequences. Reload versions use custom comparison operations.


Max: returns a larger value of the two elements. Reload versions use custom comparison operations.
Max_element: returns a ForwardIterator that specifies the largest element in the sequence. Reload versions use custom comparison operations.
Min: returns the smallest of the two elements. Reload versions use custom comparison operations.
Min_element: returns ForwardIterator, indicating the smallest element in the sequence. Reload versions use custom comparison operations.


Mismatch: Compares two sequences in parallel, indicating the first unmatched position, and returns a pair of iterator, marking the position of the first unmatched element. If all matches, the last of each container is returned. Reload versions use custom comparison operations.

 

 

Set Algorithms

 

 

<8> Set Algorithms (4)


Set_union: Construct an ordered sequence that contains all non-repeating elements in the two sequences. Reload versions use custom comparison operations.
Set_intersection: Construct an ordered sequence, where elements exist in both sequences. Reload versions use custom comparison operations.
Set_difference: Construct an ordered sequence. The sequence only retains the elements in the first sequence but not in the second sequence. Reload versions use custom comparison operations.
Set_equalric_difference: Construct an ordered sequence that obtains the symmetric difference set (Union-intersection) of the two sequences ).
 

 

Heap Algorithm

 


<9> heap algorithms (4)
Make_heap: generates a heap for elements within the specified range. Reload versions use custom comparison operations.
Pop_heap: instead of actually popping up the largest element from the heap, it sorts the heap again. It switches first and last-1, and then generates a new heap. You can use the back of the container to access the "pop-up" element or use pop_back to delete it. Reload versions use custom comparison operations.
Push_heap: If first to last-1 is a valid heap, the elements to be added to the heap are stored in last-1 and the heap is regenerated. Before pointing to this function, you must insert the element into the container. The reload version uses the specified comparison operation.
Sort_heap: sorts a sequence in a specified range. It is assumed that the sequence is an ordered heap. Reload versions use custom comparison operations.

 

 

 

 

Example:

 

Find function

 

# Include <vector> # include <algorithm> # include <iostream> using namespace std; int main () {vector <int> intv; for (int I = 0; I <10; I ++) intv. push_back (I); vector <int>: iterator inti; inti = find (intv. begin (), intv. end (), 50); if (inti = intv. end () cout <"No matched value found"; elsecout <"matched value found"; cout <endl; inti = find (intv. begin (), intv. end (), 5); if (inti = intv. end () cout <"no matching value found"; elsecout <"matched value found"; return 0 ;}

Output:

No matching value found

Matched value found

 

 

Find if Function

 

# Include "stdafx. h "# include <vector> # include <algorithm> # include <iostream> using namespace std; bool greater5 (int I) {return I> 5;} int main () {vector <int> intv; for (int I = 0; I <10; I ++) intv. push_back (I); vector <int>: iterator inti; inti = find_if (intv. begin (), intv. end (), greater5); if (inti = intv. end () cout <"no value greater than 5"; elsecout <"the first value greater than 5 is:" <* inti; // output 6 getchar (); return 0 ;}


Copy Function

 

#include "stdafx.h"#include <vector>#include <list>#include <algorithm>#include <iostream>using namespace std;int main(int argc, _TCHAR* argv[]){vector<int> intv;intv.push_back(2);intv.push_back(5);intv.push_back(3);list<int> intl;list<int>::iterator intliter;intl.push_back(6);intl.push_back(7);intl.push_back(8);intl.push_back(80);copy(intv.begin(),intv.end(),intl.begin());for(intliter=intl.begin();intliter!=intl.end();intliter++)cout<<*intliter<<"   ";  getchar();return 0;}

Output:

2 5 3 80

 

 

Repalce Function

 

#include "stdafx.h"#include <vector>#include <algorithm>#include <iostream>using namespace std;int main(){vector<int> intv;vector<int>::iterator intviter;intv.push_back(2);intv.push_back(5);intv.push_back(3);intv.push_back(50);intv.push_back(500);    replace(intv.begin(),intv.end(),5,6);for(intviter=intv.begin();intviter!=intv.end();intviter++)cout<<*intviter<<"   ";   getchar();}

Output:

2 6 3 50 500

 

 

 


 

 

 

 

 

 


STL algorithm problems

IsAToothbrush is a function object. If you can, I suggest you refer to the book to understand this concept. The function object is defined as a class that overload the () operator, while the count_if function requires a function object (I do not fully understand stl, I don't know if it is okay to pass a function pointer here, but the function object is used in this example). This object is used to traverse the elements of the set when the count_if function is executed, call operator () to determine whether to delete an element.

Djstl algorithm?

The Dijkstra (dijela) algorithm is a typical single-source shortest path algorithm used to calculate the shortest path from one node to all other nodes. The main feature is to expand horizontally at the center of the starting point until the end point is reached. Dijkstra algorithm is a representative shortest path algorithm. It is described in detail as a basic content in many professional courses, such as data structure, graph theory, and operational research. Generally, Dijkstra can be expressed in two ways: Permanent and Temporary label, and OPEN,
CLOSE the table. both permanent and temporary labels are used here. Note that this algorithm requires that no negative weight edge exists in the graph.
Problem description in undirected graph
In G = (V, E), assume that the length of E [I] of each edge is w [I], and find the shortest path from vertex V0 to other points. (Single-source shortest path)

Edit the idea of the dijela algorithm (Dijkstra) in this section.
Generate the shortest path algorithm in ascending order of path length:

Divide V into two groups:

(1) S: the set of vertices in the shortest path.

(2) V-S = T: vertex set of undefined Shortest Path

Add vertices in T to S in the ascending order of shortest paths,

Guarantee: (1) the shortest path length of each vertex from V0 to S is not greater

Shortest Path Length of any vertex from V0 to T

(2) Each vertex corresponds to a distance value.

Vertex in S: the shortest path length from V0 to this Vertex

Vertices in T: From V0 To This vertex only contains vertices in S as the center

Shortest Path length of a vertex

Basis: it can prove the Shortest Path of the Vk from V0 to T, or from V0 to Vk

The weight of the direct path, or the sum of the path weights from the top point of the V0 through S to the Vk

(The Reverse verification method is verifiable)

Steps for finding the Shortest Path
The algorithm steps are as follows:

1. The distance values of S = {V0}, T = {other vertices}, and T in the first season

If <V0, Vi> and d (V0, Vi) exist, they are the weights on the <V0, Vi> arc.

If <V0, Vi> and d (V0, Vi) do not exist

2. Select a vertex W whose distance value is the smallest from T and is not in S. Add S.

3. Modify the distance value of the vertex in S: If W is added as the intermediate vertex

If the distance value is shortened, modify the distance value.

Repeat steps 2 and 3 until S contains all vertices, that is, W = Vi.

Edit the principle of the dijela algorithm in this section. First, introduce an auxiliary vector D. Each component D indicates the length of the shortest path found from the starting point v to the end point vi. For example, D [3] = 2 indicates that the relative minimum length of the path from start point v to end point 3 is 2. It is emphasized that the value of D is constantly approaching the final result in the algorithm process, but it is not necessarily equal to the shortest path length in the process. Its initial state is: if there is an arc from v to vi, D is the weight of the arc; otherwise, D is set to ∞. Obviously, the length is
D [j] = Min {D | vi ε V} is the shortest path with the shortest length starting from v. This path is (v, vj ).
Which of the following is the short Shortest Path? If the end of the short path is vk, you can imagine that this path is either (v, vk) or (v, vj, vk ). Its length is either the weight of the arc from v to vk, or the sum of the weight of D [j] and the weight of the arc from vj to vk.
Generally, if S is the set of the end points of the obtained shortest path, it can be proved that the next Shortest Path (set its end point to X) or the arc (v, x ), or the path that finally reaches vertex X only after the vertex in S in the middle. Therefore, the length of the next short shortest path must be D [j] = Min {D
| Vi, V-S} Where, D or the weight on the arc (v, vi), or D [k] (vk, S) and the arc (vk, vi) the sum of the weights. The dijela algorithm is described as follows:
1) arcs indicates the weight on the arc. If not, set arcs to ∞ (MAXCOST in this program ). S is the set of the end points of the shortest path from v. the initial state is empty. Then, output from v... the remaining full text>
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.