C++11里面的Lambda表达式 (三)

2014-11-23 22:08:32 ? 作者: ? 浏览: 7
the vector by
// using the for_each function and a function object.
int evenCount = 0;
for_each(v.begin(), v.end(), FunctorClass(evenCount));

// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}

// even_functor.cpp
// compile with: /EHsc
#include
#include
#include
using namespace std;

class FunctorClass
{
public:
// The required constructor for this example.
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 silence 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 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.begin(), v.end(), FunctorClass(evenCount));

// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: