Basic----Generic algorithm

Source: Internet
Author: User

The algorithm does not depend on the container (using iterators), but most of them depend on the element type. If find requires the = = operator, other algorithms may require support < operators.

The algorithm never performs a container operation and never changes the size of the underlying container (add or remove elements).

The Accumulate (V.cbegin (), V.cend (), String ("")) algorithm accumulates an operator, and the type of the 3rd parameter determines which + operator to use.

Equal (V1.cbegin (), V1.cend (), V2.cbegin ()), comparing two sequences on a case-by-case basis. The second sequence is at least as long as the first sequence.

The container and element types do not have to be the same, as long as the = = Symbol compares two element types.

Those algorithms that accept only a single iterator to represent the second sequence, assume that the second sequence is at least the first equal length.

It is the responsibility of the programmer to ensure that the algorithm does not access elements that do not exist in the second sequence.

Algorithm that writes data to the destination iterator without checking the write operation surface

Auto it = Back_inserter (VEC);//Returns an insert iterator that, when used to assign a value, calls Push_back to add the element to the container.

Fill_n (it,10,0); Add 10 elements to a VEC.

Many algorithms provide a copy version, which returns a copy, and the original sequence does not change.

Sort (Words.begin (), Words.end ());//Sort

Auto End_unique = unique (Words.begin (), Words.end ());//deduplication, returns a position after the non-repeating area

Words.erase (End_unique,words.end ());//algorithm can not be directly removed or deleted, call erase Delete redundant elements

Instant words no duplicate elements, this operation is also safe

predicate (predicate)

The callable expression that returns the result is a value that can be used as a condition .

Use predicates instead of the default operations of the algorithm, such as defining the two-isshorter function, instead of the sort default < comparison element.

Sort (Words.begin (), Words.end (), isshorter);

Stable_sort (Words.begin (), Words.end (), isshorter);//Maintain the original ordering of equal elements

The partition divides the container into two parts, true before. Partition_stable maintaining the order of the original elements

Callable Object

Functions, function pointers, function objects, lambda expressions (which can be understood as an unnamed inline function)

[Capture List] (parameter list), return type {function Body}

Where the parameter list and return type can be omitted, but the capture list and function body must always be included.

Ignore argument list equivalent to empty argument list

The return type is ignored, and if there is only one return statement for the function body, it is judged from the type of the expression, and void is returned if any other statements are included.

Lambda

Cannot have default parameters

Lambda only captures a local variable of its function in its capture list before the variable is used in the body of the function. Only local non-static variables, local static and variables declared outside the function can be used directly.

Make_plural (count, "word", "s")//differentiate single complex number, count is 1 singular

Find_if (Words.begin (), Words.end (), [SZ] (const string &a) {return a.size () >=sz;});

For_each (Wc,words.end (), [] (const string &s) {cout<<s<< "";});

Sort-deduplication-delete superfluous-sort by length-find the beginning of length greater than SZ, print

Value capture

The premise is that the variable can be copied, and the value of the captured variable is copied when the lambda is created, not when it is called.

Reference capture

You need to ensure the validity of the captured local variables, or you can return a lambda from the function and not include a reference capture of the local variable. If possible, try to avoid capturing pointers or references.

Lambda Capture List

[]

Empty Capture List

[Names]

List of names, which are copied by default

[&]

Implicit capture lists, all with reference captures

[=]

Implicit capture lists, all with value capture

[&,identifier_list]

Except for the individual value capture

[=, identifier_list]

Except for individual reference captures

Variable lambda

The default does not change the value of the variable being captured, as you want to change, using mutable.

Lambda expressions are most useful for simple operations that are used only in one or two places.

For the same operation that is used in many places, or if an operation requires a lot of statements to complete, it is usually better to define a function.

A lambda with an empty capture list can usually be substituted with a function;

And for the capture variable, it's not that easy. will face the problem of inconsistent number of predicate parameters.

Bind function (function adapter)

Accepts a callable object and generates a new callable object to accommodate the original object's argument list.

Auto newcallable = bind (callable, arg_list);

The arg_list corresponds to the callable parameter. It may contain a name in the form of _n, which occupies the nth position passed to the newcallable parameter.

BOOL Check_size (const string& S, String::size_type sz) {return s.size () >= sz;}

Auto Check6 = bind (Check_size, _1, 6);//

The bind call has only one placeholder, that is, CHECK6 receives only one parameter, and the placeholder appears in the first position of the first arg_list, indicating that check6 this parameter corresponds to Check_size's first parameter, const string&.

Auto G =bind (F, A, B, _2, C, _1),//f has 5 parameters, where _1 and _2 correspond to the 1th and 2nd parameters of G respectively

G (_1,_2) maps to F (A, B, _2, C, _1)

Need to include namespaces using std::p laceholders::_1;

Using namespace std::p laceholders;

For parameters that are not placeholders, the default is to copy to the callable object returned by bind, and sometimes you need to pass ref (OS) as a reference, and cref () generates a const reference.

Bind ref CREF is in the header file functinal.

Note: bind1st and bind2nd can only bind the first or second parameters, respectively, due to the limitations of the new standard has been deprecated. binder1st and binder2nd are similar, but they are the type of op that the template class needs to specify

bind1st (OP, Value) (x), OP (value,x)

bind2nd (Op,value) (x), OP (x,value)

Other iterators

Insert iterator: Binds to the container and can insert elements into the container

Stream iterators: Binding to an input-output stream, which can traverse the associated IO stream, as long as an object with the << or >> operator is defined

Reverse iterator: Move backwards, forward_list no

Move iterators: Instead of copying the elements in them, move them.

Inserting iterators

*it, ++it, it++ won't do anything for it, return it

Back_inserter push_back

Front_inserter Push_front

Inserter Insert

As Inserter generated iterators do the following assignment operation *it = Val;

The effect is equivalent to the following code

it = C.insert (it, Val);//it points to the newly added first element

++it;

With different insert iterators, the resulting sequence of sequences will be different.

Stream iterators

You must create the type of object you want to read and write, bind it to a stream when you create it, or initialize the iterator by default when the tail-end iterator is used.

Istream_iterator<int> In_iter (CIN);

Istream_iterator<int> EOF;

while (in_iter!=eof)

Vec.push_back (*in_iter++);

Can be changed into the following form

Istream_iterator<int> In_iter (CIN), EOF;

Vector<int> VEC (In_iter, EOF); Constructing VEC from the scope of an iterator

Data read from the stream to construct the VEC

Combine with some algorithms to process streaming data. Input stream iterators can be used as source iterators, input as Target iterators

such as Cout<<accumulate (in, EOF, 0) <<endl;

Istream_iterator allows lazy evaluation to postpone reading data in mid-stream. The standard library guarantees that the operation to read data from the stream has been completed before the first dereference.

If an iterator can be destroyed, or if two objects synchronize with a stream, then it is important to read it.

Ostream_iterator allows the second argument, a C-style string, to be printed after each element is output. Must be bound to a stream.

*out, ++out, out++ provide form support and will not do anything

Ostream_iterator<int> Out_iter (cout, "");

for (auto E:vec)

*out_iter++ = e;

cout<<endl;

Both * and + + can be ignored, but the recommended notation can be kept consistent with the use of other iterators, easy to modify, and clearer to the reader.

Reverse iterator

Allows us to use algorithms to transparently process containers forward or backward.

The need to support both + + and--,forward_list and stream iterators cannot be created.

When a reverse iterator is used, it is reversed at print time and needs to be converted using the base member.

[Line.crbegin (), Rcomma) and [Rcomma.base (), Line.end ()) point to the same element range in line.

In addition, the range represented by the reverse iterator is asymmetric, and its point is not the same when the reverse iterator is initialized from a normal iterator or assigned a value.

5 Types of iterators

Iterator category

Input iterators

Read-only, do not write, single-pass scan, only increment

Output iterators

Write only, not read, single-pass scan, only increment

Forward iterators

Can read and write, multiple times scan, only increment

Bidirectional iterators

Can read and write, multiple times scan, can increment decrement

Random-Access iterators

Read-write, multiple-pass scan, support for all iterator operations

The algorithm indicates the smallest class of iterator parameters, such as an error if the passed iterator parameter is substantially lower.

Input iterators:

at least = =,! =, front and back + +, dereference * (right of Assignment),

The *it++ guarantee is valid, but incrementing may cause other iterators to fail, and there is no guarantee that the state of the input iterator can be saved and used to access the element. So it can only be used for single-pass scanning algorithms.

such as find and accumulate support istream_iterator

Output iterator: (Can be seen as a complement to an input iterator)

Support at least front and rear + +, dereference * (left of assignment), can only be assigned to an output iterator once, single-pass scan.

such as copy of the 3rd parameter, Ostream_iterator

Forward iterators:

Replace, Forward_list

Bidirectional iterators: (--)

Reverse

Random-access iterators:

< <= > >= + + =-= two iterators subtract subscript operator

Sort array deque pointer to a string vector built-in array element

Common algorithm formal parameter types

ALG (Beg, end, other args);

ALG (Beg, End, dest, other args);

ALG (Beg, End, BEG2, other args);

ALG (Beg, End, BEG2, End2, other args);

The algorithm that accesses the data to the output iterator is assumed to be sufficient for the target space.

The algorithm for a single BEG2 assumes that the sequence starting from BEG2 is at least as large as sequence 1.

Algorithm naming conventions

Overloading passes a predicate

The _if version will accept an element value version to accept a predicate version, using a different function name to avoid possible overloading ambiguity.

Copy version

The algorithm for the default Reflow element writes back to the input sequence, and the copy version is written to a specified output destination.

Linked list type-specific algorithms

Other general-purpose algorithms can also be used for linked lists, but are too expensive to exchange elements. A linked list can be exchanged by changing the link without actually exchanging elements. Therefore, the member function version is used preferentially.

List Forward_list member function version algorithm (both return void)

Lst.merge (LST2)

Merge, all two must be ordered, and Lst2 are empty after merging

Lst.merge (Lst2,comp)

Ditto, using the predicate given by the comparison operation

Lst.remove (Val)

Erase deleting elements

Lst.remove_if (pred)

Ditto

Lst.reverse ()

Reverse sequence

Lst.sort ()

Sort using < or a given comparison operation

Lst.sort (COMP)

Lst.unique ()

Delete the same worth continuous copy

Lst.unique (pred)

Ibid., using a two-dollar predicate

Splice Members

Lst.splice (args) or flst.splice_after (args)

(p, Lst2) moves all elements in the lst2 into the LST before p or flst p, the elements are removed from the lst2 and cannot be the same linked list

(p, Lst2, p2) moves the element that the P2 points to the LST, which can be the same list

(P, Lst2, B, e) Moves the elements pointed between B and e into the LST, which can be the same linked list, but cannot contain p.

A key difference between a list-specific version is that it changes the underlying container.

Basic----Generic algorithm

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.