The unique role of for_each () in function objects

Source: Internet
Author: User

For_each can traverse the values of list and vecotr, pass one of the values to the function object, call the () Operator for reload, and put the final calculation result into a function object to return. this function is otherAlgorithmNone. The usage is as follows.

 

# Include <iostream. h>
# Include <iterator>

# Include <string>

# Include <vector>
# Include <deque>
# Include <list>
# Include <algorithm>
# Include <map>
# Include <set>

Using namespace STD;

Class mean
{
Public:
Mean (): m_value (0), m_sum (0 ){}//
Void operator () (INT Ele) {m_value ++, m_sum + = ele;} // ELE is the value passed in by the overload function.
Public:
Int m_value;
Int m_sum;
};

Void main ()
{

Vector <int> m_vec (4 );
M_vec [0] = 1;
M_vec [1] = 2;
M_vec [2] = 3;
M_vec [3] = 4;

Mean Me = for_each (m_vec.begin (), m_vec.end (), mean (); // mean () to generate a temporary object, and for_each will call to generate a temporary object, then, call the () operator to reload the function through a temporary object. assign the final temporary object to me
Cout <me. m_sum <Endl; // The sum value is 10.
Cout <me. m_value <Endl; // The total number is 4
 

}

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.