C ++ 11 Study Notes-Lambda expressions (comparison and test Lambda, bind, Function Object)

Source: Internet
Author: User

C ++ 11 Study Notes-Lambda expressions (comparison and test Lambda, bind, Function Object)
All c ++ coder should be happy with this syntax. Simply put, Lambda expressions are the syntactic sugar of function objects. Let's just look at the comparison. We copied the example from the official msdn website. We used the lambda embedded in the for_each function call to print to the console whether each element in the vector object is an even number or an odd number. Use lambda to copy the Code # include <algorithm> # include <iostream> # include <vector> using namespace std; int main () {// Create a vector object that contains 10 elements. vector <int> v; for (int I = 0; I <10; ++ I) {v. push_back (I);} // Count the number of even numbers in the vector by // using the for_each function and a lambda. int evenCount = 0; for_each (v. begin (), v. end (), [& evenCount] (int n) {cout <n; I F (n % 2 = 0) {cout <"is even" <endl; ++ evenCount ;} else {cout <"is odd" <endl ;}}); // Print the count of even numbers to the console. cout <"There are" <evenCount <"even numbers in the vector. "<endl;} copy the code using Function Object to copy the Code # include <algorithm> # include <iostream> # include <vector> using namespace std; class FunctorClass {public: // The required constructor for this exa Mple. explicit FunctorClass (int & evenCount): m_evenCount (evenCount) {}// The function-call operator prints whether the number is // even or odd. if the number is even, this method updates // the counter. void operator () (int n) const {cout <n; if (n % 2 = 0) {cout <"is even" <endl; + + m_evenCount;} else {cout <"is odd" <endl;} private: // Default assignment operator to silen Ce warning C4512. FunctorClass & operator = (const FunctorClass &); int & m_evenCount; // the number of even variables in the vector .}; int main () {// Create a vector object that contains 10 elements. vector <int> v; for (int I = 0; I <10; ++ I) {v. push_back (I);} // Count the number of even numbers in the vector by // using the for_each function and a function object. int evenCount = 0; for_each (v. be Gin (), v. end (), FunctorClass (evenCount); // Print the count of even numbers to the console. cout <"There are" <evenCount <"even numbers in the vector. "<endl;} as Microsoft documents have said, there is no substantial gap between the two methods in efficiency. I have tested them myself, there is no difference in both debug and release modes. I accidentally found the bind and Lambda comparison tests at night. The first three methods were online, and the last two were added by myself. The results definitely broke my eggs. Copy the Code # include <cstdint> # include <chrono> # include <iostream> # include <string> # include <thread> # include <vector> # include <algorithm> # if USE_BOOST # include <boost/function. hpp> # include <boost/bind. hpp> # endif class FunctorClass {public: // The required constructor for this example. explicit FunctorClass (uint64_t & evenCount): m_evenCount (evenCount) {}// The function-call operator prints whether the nu Mber is // even or odd. if the number is even, this method updates // the counter. void operator () (int n) const {m_evenCount + = n;} private: // Default assignment operator to silence warning C4512. FunctorClass & operator = (const FunctorClass &); uint64_t & m_evenCount; // the number of even variables in the vector .}; class timer {public: typedef std: chrono: high_resolution_clock clock; typedef cloc K: time_point; typedef clock: duration; public: timer () {reset ();} void reset () {_ starttime = clock: now ();} duration elapsed () const {return clock: now ()-_ starttime;} protected: time_point _ starttime;}; bool test_timer () {using std: chrono: milliseconds; typedef timer: duration; const milliseconds sleep_time (500); timer t; std: this_thread: sleep_for (sleep_time ); Duration recorded = t. elapsed (); // make sure the clock and this_thread: sleep_for is precise within one millisecond (or at least in agreement as to // how inaccurate they are) return (recorded-milliseconds (1) <sleep_time) & (recorded + milliseconds (1)> sleep_time);} template <typename T> void volatile_write (const T & x) {volatile T * p = new T; * p = x; delete p;} template <typename Function> Void run_test (const std: string & name, Function func) {std: cout <name; timer t; volatile_write (func (); timer :: duration = t. elapsed (); std: cout <'\ t' <duration. count () <std: endl;} template <typename Function> void do_test_loop (Function func, const uint64_t upper_limit = extends ull) {uint64_t I; for (I = 0; I <upper_limit; ++ I) func (I); if (I = upper_limit) {std: cout <I ;}} Uint64_t test_accumulate_lambda () {uint64_t x = 0; auto accumulator = [& x] (uint64_t I) {x + = I ;}; do_test_loop (accumulator); return x ;} void encode (uint64_t & x, uint64_t I) {x + = I;} uint64_t test_accumulate_bind () {namespace arg = std: placeholders; uint64_t x = 0; std :: function <void (uint64_t)> accumulator = std: bind (& test_accumulate_bind_function, std: ref (x), arg: _ 1 ); Do_test_loop (accumulator); return x;} uint64_t test_accumulate_bound_lambda () {uint64_t x = 0; std: function <void (uint64_t)> accumulator = [& x] (uint64_t I) {x + = I ;}; do_test_loop (accumulator); return x ;}uint64_t test_accumulate_class_function () {uint64_t x = 0; do_test_loop (FunctorClass (x); // for_each (v. begin (), v. end (), FunctorClass (x); return x;} uint64_t test_accumulate_bind_auto (){ Namespace arg = std: placeholders; uint64_t x = 0; auto accumulator = std: bind (& test_accumulate_bind_function, std: ref (x), arg: _ 1 ); do_test_loop (accumulator); return x ;}# if USE_BOOSTuint64_t evaluate () {uint64_t x = 0; boost: function <void (uint64_t)> accumulator = boost :: bind (& test_accumulate_bind_function, boost: ref (x), _ 1); do_test_loop (accumulator); return x;} uint64_t Test_accumulate_boost_bound_lambda () {uint64_t x = 0; boost: function <void (uint64_t)> accumulator = [& x] (uint64_t I) {x + = I ;}; do_test_loop (accumulator); return x ;}# endif int main () {if (! Test_timer () {std: cout <"Failed timer test. "<std: endl; return-1;} run_test (" Accumulate (lambda) ", & test_accumulate_lambda); run_test (" Accumulate (bind) ", & test_accumulate_bind ); run_test ("Accumulate (bound lambda)", & role); run_test ("Accumulate (Function Object)", & test_accumulate_class_function); run_test ("Accumulate (bind auto )", & test_accumulate_bind_auto); # if USE_BOOST run_test ("Accumulate (boost bind)", & role); run_test ("Accumulate (boost bound lambda)", & test_accumulate_bound_lambda ); # endif} copy the code debug mode: Accumulate (lambda) 100000000 422885105 Accumulate (bind) 100000000 4346676523 Accumulate (bound lambda) 100000000 1707092933 Accumulate (class function) 100000000 494674507 Accumulate (bind auto) 100000000 3381097610 Release mode Accumulate (lambda) 100000000 17978 Accumulate (bind) 100000000 607188485 Accumulate (bound lambda) 100000000 520421500 Accumulate (Function Object) 100000000 1925 Accumulate (bind auto) 100000000 1726

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.