C + + Primer 5th notes: Tenth Chapter

Source: Internet
Author: User

The tenth chapter: generic algorithm

Notes

1. The standard library does not add a lot of functionality to each container, but rather provides a set of algorithms , most of which are independent of any particular container.

2. Most algorithms are defined in the header file algorithm , and a set of numeric generic algorithms are defined in the header file numeric .

3. Ensure that the algorithm has sufficient element space to open the output data by using an insert iterator, Back_inserter accepts a reference to the container and returns an insert iterator bound to the Container:

 vector<int  > vec; //      empty vector  Auto it = Back_inserter (vec); //     Assigning an element  adds  it to the VEC     *it = 42 ; //    There is now an element in the VEC with a value of   //     We often use Back_inserter to create an iterator that is used as the purpose of the algorithm to use the   fill_n (back_inserter (vec), 10 , 0    ); //   

4. A predicate is a callable expression whose return result is a value that can be used as a Condition. The predicates used by the standard library algorithm fall into two categories: unary predicates (which means they only accept single arguments) and two-tuple predicates (meaning they have two parameters). The algorithm that accepts the predicate argument invokes the predicate on the element in the input sequence . such as:

// comparison function, used to sort words by length bool isshorter (conststringconststring &s2) {   return s1.size () < s2.size (); }  // by length from short to long sort wordssort(words.begin (), words.end (), isshorter);        

5. iterators include: Insert iterators, stream iterators, reverse iterators, move Iterators.

6. Insert Iterator: Back_inserter Create an iterator that uses PUSH_BACK.

Front_inserter creates an iterator that uses PUSH_BACK.

Inserter Create an iterator that uses insert. This function takes the second argument, which must be an iterator to a given container. The element is inserted before the element represented by the given Iterator.

7. The most basic characteristic of any algorithm is the actions it requires its iterators to provide .

Summary of key points of knowledge:

    one,Lambda expression:

1. Introduction to Lambda

We can pass any class of callable objects (callable Object)to an algorithm. For an object or an expression, if you can use the call operator (that is, parentheses ()), it is called Callable. A lambda expression represents a callable unit of code . We can interpret it as an unnamed inline function. a lambda expression has the following form:

[capture list] (parameter list), return type { function body }

Where capturelist is a list of local variables defined in a lambda function (usually empty);return type, paramete list, and function body as with any normal function, the return type, the argument list, and the body of the function are represented respectively. however, Unlike a normal function, a lambda expression must be returned using a Tail. Such as:

return ; };   // defines a callable object f, which does not accept parameters, returns a // Lambda is called in the same way as normal function calls, using the call operator cout << F () << endl;  // Print      

if the function body of a lambda contains nothing other than a single return statement, and no return type is specified, void is returned by Default.

      2. passing parameters to lambda

// Sort by length stable_sort (words.begin (), words.end (),          [] (    conststringconst       String &s2)                   return s1.size () < s2.size ();}  //  Lambda cannot have a default argument  //  empty capture list indicating that this lambda does not use any of the local variables in its function      

      3. Using the Capture list

        Although Lambda can appear in a function, use its local variables , it can only use variables that are explicitly specified in the capture list .

[sz] (conststringreturn a.size () >= sz;};

      4. Using lambda in find_if and For_each algorithms

//gets an iterator that points to the first element that satisfies the size () >= sz, which is a local variableAuto WC =find_if (words.begin (), words.end (), [sz] (Const string&A) {returnA.size () >=sz;}); //print a word that is longer than or equal to a given value, followed by a space after each wordFor_each (wc, words.end (), [] (Const string&S) {cout<< s <<" ";}      ); cout<<endl; //a lambda can directly use names that are defined outside of the current Function.       //cout is not defined as a local name in the local scope of the code, but is defined in the header file Iostream. //therefore, as long as the header file iostream is included, you can use the cout

      5. Lambda Capture and return

        When a lambda is defined, the compiler generates a new (unnamed) class type corresponding to the LAMBDA. when a lambda is passed to a function, a new type and an object of that type are defined: the passed argument is an unnamed object of the class type generated by this compiler .

Similar to parameter passing, the way a variable is captured can also be a value or reference .

// Value Capture Method , the assumption is that the variable can be copied        voidfcnl () {size_t v1= the;//Local Variables//Copy the V1 to a callable object named FAuto F = [v1] {returnv1;}; V1=0; Auto J= f ();//J saved a copy of V1 when we created it for 42,;f.}//Unlike parameters, the value of the captured variable is copied at Lamba creation time, not when it is called// Reference Capture , where you can capture variables by reference when you define a lambda       voidfcn2 () {size_t v1= the;//Local Variables//Object F2 contains references to V1            Auto F2 = [&v1] { return  v1;}; V1=0; Auto J= F2 ();//J is 0; F2 save V1 references, not copies}

when A variable is captured as a reference, it must be guaranteed to exist when the variable is executed by the LAMBDA. Minimize the amount of data captured to avoid potential capture-induced Problems.

       6. Implicit capture

          In addition to explicitly exhausting the variables that we want to use from the function you are using, you can also have the compiler infer which variables we want to use based on the code in the lambda body. In order to instruct the compiler to infer the capture list, write a & or =in the capture list,& tell the compiler to take a capture reference ,= to take a value capture method . Such as:

//sz for implicit capture, value capture modeWC =find_if (words.begin (), words.end (), [=](Const string&S) {returnS.size () >=sz;      } ); //If we take a value capture of some of the variables and use reference captures for other variables, we can mix implicit captures//and display capture//OS implicit capture, reference capture mode, C Explicit capture, value capture method        for_each (words.begin (), words.end (), [&, c] (Const string&s) {os << S <<c;}      ); //OS explicit capture, reference capture mode, C Implicit capture, value capture method        for_each (words.begin (), words.end (), [=, &os] (Const string&s) {os << S <<c;}      ); //attention!! When we mix implicit capture and explicit capture, the first element in the capture list must be a//& or =. This symbol specifies the default capture method as a reference or a Value. And all explicit capture methods must be//unlike The default capture method, it is placed behind & or =. 

7. Specify the lambda return type

By default, If a lambda body contains any statements other than return, the compiler (if the return type is not explicitly specified) assumes that this lambda returns VOID.

      second, standard library bind function (to be Written)

Terms

Binary predicate (binary predicate), callable Object (callable object), capture list, Insert (inserter),

Generic algorithms (generic algorithm), predicates (predicate), Lambda expressions, reverse iterators (reverse iterator),

Stream Iterator.

2016-11-11 22:44:46

C + + Primer 5th notes: Tenth Chapter

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.