Chapter 2 generic algorithms

Source: Internet
Author: User

 

1. Introduction

Containers in the standard library define very few operations. Instead of adding a large number of functional functions to the container, the standard library provides a set of algorithms that do not depend on the specific container type, it is generic and can be applied to different types of containers and elements.

The standard container defines few operations: add and delete elements, access the first and last elements, obtain the container size, and reset the container size in some cases, and get the iterator pointing to the next position of the first element and the last element.

You also want to perform more useful operations on container elements, such as sorting elements in the ordered container, searching for a specific element, or searching for the largest or smallest element. The standard library does not define the member functions that implement these operations for each container type). Instead, it defines a set of "generic algorithms" because they implement common operations, therefore, they are called "algorithms", while "generic" means that they can operate on a variety of container types-not only in standard library types such as vector and list, it can also be used in the built-in array type.

Most algorithms implement functions by traversing the Elements marked by two iterators.

2. Common generic algorithms

1) find algorithm (read-only algorithm)

Call the find function using two iterators and one value to check each element within the range marked by the real parameters of the two iterators, as long as it finds that it is equal to the given value, find returns the iterator pointing to this element. If no matching element exists, find returns its second iterator real parameter, indicating that the search fails. Therefore, you only need to check whether the return value of the function is equal to the second real parameter, and then you can know whether the element is found.

A simple example:

Int search_value = 42;

Vector <int>: const_iterator result = find (vec. begin (), vec. end (), search_value );

If (result = vec. end ())

Cout <"not present" <endl;

Else

Cout <"present" <endl;

(2) read-only accumulate algorithm)

The first two Parameters specify the range of elements to be accumulated. The third parameter is the initial value of accumulation. The algorithm returns the result of accumulation. The return type is the type of the third real parameter.

A simple example:

Int sum = accumulate (vec. begin (), vec. end (), 42 );

String sum = accumulate (v. begin (), v. end (), string (""));

(3) fill Algorithm write algorithm)

Write the value to the specified range of the target iterator. The first two indicate the filling range.

A simple example:

Fill (vec. begin (), vec. end (), 0 );

Assign a value of 0 to all elements in the vec container;

(4) fill_n algorithm (write algorithm)

Fill_n (vec. begin (), 10, 0)

Assign 0 to the 10 elements at the beginning of the vec container. If the container is empty or the number of elements in the current container is less than 10, an error occurs.

Back_inserter): inserts an iterator. Use a container object as a real parameter. Back_inserter generates an insert iterator bound to the container. When trying to assign a value to an element through this iterator, the value assignment operation will call push_back to add an element with a specified value to the container. As follows:

Vector <int> vec;

Fill_n (back_insert (vec), 10, 0)

In this way, no error occurs. Each time the fill_n function writes a value, it will be implemented through the insert iterator generated by back_inserter. The effect is equivalent to calling the push_back function on vec. Add 10 elements to the end of vec, and the value of each element is 0.

5) copy algorithm (write algorithm)

Vector <int> ivec;

Copy (ilst. begin (), ilst. end (), back_inserter (ivec ));

Copy all elements in ilst to the ivec container. In fact, this efficiency is not high. You can use ilst to initialize the new container when constructing it, for example:

Vector <int> ivec (ilst. begin (), ilst. end ());

6) replace Algorithm (write algorithm)

There are four real parameters. The first two are the search range for replacement, 3rd are the values to be replaced, and 4th are the replacement values, for example:

Replace (ilst. begin (), ilst. end (), 0, 42)

Find 0 in the ilst container and replace it with 42.

7) replace_copy algorithm (write algorithm)

If you do not want to change the original sequence, you can call replace_copy. This algorithm receives the real parameters of the 3rd iterators and specifies the target position of the adjusted sequence.

For example:

Replace_copy (ilst. begin (), ilst. end (), back_inserter (ivec), 0, 42 );

After this function is called, The ilst is not changed, and the ivec stores the replaced copy.

8) sort Sorting Algorithm

Sort (words. begin (), words. end ());

Elements in the container are arranged alphabetically.

9) unique algorithm:

Suitable for sorting containers, deleting adjacent duplicate elements. The algorithm returns the next position that exceeds the end of the element range without duplicates.

For example:

Vector <string>: iterator end_unique = unique (words. begin (), words. end ());

Words. erase (end_unique, words. end ());

(10) stable_sort Algorithm

The sort algorithm arranges elements in a given range from small to large. The stable_sort algorithm adds a parameter called a predicate to control the Ordering Based on what principles.

For example, bool IsShort (const string & s1, const string & s2)

{

Return s1.size () <s2.size ();

}

Stable_sort (words. begin (), words. end (), IsShort );

It is sorted by the length of the element string.

11) count_if Algorithm

The number of elements that meet a certain condition in the container must be recorded. A predicate is also required to describe the rule.

For example, bool GT6 (const string & s)

{

Return s. size ()> = 6;

}

Vector <string >:: size_type wc = count_if (words. begin (), words, end (), GT6 );

Summary:

The container and algorithm library are the basis of the standard library. The standard library defines more than 100 algorithms. Fortunately, these algorithms have the same structure, making them easier to learn and use.

Algorithms are not related to types. They generally operate on an element sequence. These elements can be stored in standard container types, built-in arrays, or even generated sequences.

The algorithm is based on iterator operations to achieve type independence.

Most algorithms use an iterator with a specified Element range as the first two real parameters. Other real parameters of the iterator include the output iterator of the specified output target, or another or a pair of iterators that specify the second input sequence.

The algorithm used to search for a value generally provides the second version, which is used to search for elements that make the predicate return a non-zero value. For this algorithm, the function name of the second version is indicated by the _ if suffix. Similarly, many algorithms provide the so-called copy version to write modified) elements to the output sequence instead of writing them back to the input range. The version name is _ copy.

 

This article is from "Li Haichuan" blog, please be sure to keep this source http://lihaichuan.blog.51cto.com/498079/1291886

Related Article

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.