Functions object State (Function objects) get--Reference pass and For_each ()

Source: Internet
Author: User

In general, the function object default value is passed, and its state cannot be obtained. This article obtains the function object state in both the reference pass and the For_each () method.

Passing function object by reference

Example of passing a function object in a reference way:

#include <iostream>#include <list>#include <algorithm>#include <iterator>using namespace STD;Template<TypeNameT>voidPrint_elems (T coll) { for(AutoElem:coll) {cout<< Elem <<"'; }cout<< Endl;}classintsequence{Private:intValue_; Public: Intsequence (intInitial_value)//Constructors: Value_ (initial_value) {}int operator() ()//"function call"{return++value_; }};intMain () { list<int>Coll Intsequence seq (1);//Insert 4 elements, reference Pass, will save the final valuegenerate_n<back_insert_iterator< list<int>,int, Intsequence&> (Back_inserter (coll),//Insert Element        4,//4 elementsSEQ);//Generate DataPrint_elems (coll);//Insert four elements starting with 42Generate_n (Back_inserter (coll),4, Intsequence ( the)); Print_elems (coll);//Repeat the first sequence SEQ, value Pass call, will start with the original saved value 5Generate_n (Back_inserter (coll),4, seq); Print_elems (coll);//Repeat the first sequence seq again, value Pass call, will start with the original saved value 5Generate_n (Back_inserter (coll),4, seq);    Print_elems (coll); System"Pause");}

The result of the operation (Linux environment results, the result of VS2013 environment is the value pass, do not know why: ):

2 3 4 52 3 4 5 43 44 45 462 3 4 5 43 44 45 46 6 7 8 92 3 4 5 43 44 45 46 6 7 8 9 6 7 8 9

Program Analysis:
The first time you call Generator_n (), the function object seq is passed as a reference, and the template argument is clearly labeled:

generate_n<back_insert_iterator<list<int>int, IntSequence&>            (back_inserter(coll),           //插入元素            4,                              //4个元素            seq);                           //生成数据

After the call, the SEQ internal value is changed.

The sequence generated by the third call to SEQ will follow the sequence produced by the first call. Because it is a value-passing SEQ:

generate_n(back_inserter(coll), 4, seq);

So this call does not change the SEQ state.
So the last time you call Generate_n (), the sequence starts at 5.

For_each () call

For the following example of For_each (), the average of a sequence is processed:

#include <iostream>#include <vector>#include <algorithm>using namespace STD;classmeanvalue{Private:LongNum_;LongSum_; Public: Meanvalue (): Num_ (0), Sum_ (0){    }//function Call    void operator() (intElem) {++num_;    Sum_ + = Elem; }DoubleValue () {return static_cast<Double> (sum_)/static_cast<Double> (num_); }};intMain () { vector<int>coll = {1,2,3,4,5,6,7,8}; Meanvalue mv = For_each (Coll.begin (), Coll.end (), Meanvalue ());cout<<"mean value:"<< mv.value () << Endl; System"Pause");}
/*运行结果mean value :4.5请按任意键继续. . .*/

Program Analysis:
The Meanvalue () expression produces a function object that records the number of elements and computes the sum of the elements.
Pass this function object to For_each (), which invokes the function object for each element within the container coll:

MeanValue mv = for_each(coll.begin(), coll.end(), MeanValue());

The returned function object is assigned to the MV and can be called mv.value () to query its state.

Function Object state get--reference pass and For_each ()

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.