C++11 lambda函数符

#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<ctime>
const long Size1 = 39L;
const long Size2 = 100 * Size1;
const long Size3 = 100 * Size2;
bool f3(int x) {return x % 3 == 0 ;}
bool f13(int x) {return x % 13 == 0;}

int main() {
    using std::cout;
    std::vector<int>numbers(Size1);
    std::srand(std::time(0));
    std::generate(numbers.begin(),numbers.end(),std::rand);

    cout << "sample size " << Size1 << std::endl;
    int count3 = std::count_if(numbers.begin(),numbers.end(),f3);
    cout << "count of numbers divisable by 3 " << count3 << std::endl;
    
    int count13 = std::count_if(numbers.begin(),numbers.end(),f13);
    cout << "count of numbers divisable by 13" << count13 << std::endl;

    numbers.resize(Size2);
    std::generate(numbers.begin(),numbers.end(),std::rand);
    cout << "sample size" << Size2 << std::endl;

    class f_mod {
    private :
    int dv;
    public :
    f_mod(int d = 1) : dv(d) { }
    bool operator () (int x) { return x % dv == 0; }
    };

    count3 = std::count_if(numbers.begin(),numbers.end(),f_mod(3));
    cout << "count of number div by 13" << count3 << std::endl;

    numbers.resize(Size3);
    std::generate(numbers.begin(),numbers.end(),std::rand);
    cout << "sample size" << Size3 << std::endl;
    count3 = std::count_if(numbers.begin(),numbers.end(),[](int x) {return x % 3 == 0 ; });
    cout << "count3 = " << count3 << std::endl;

    return 0;
}
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<ctime>
const long Size = 390000L;
int main() {
    using std::cout;
    std::vector<int>numbers(Size);
    std::srand(std::time(0));
    std::generate(numbers.begin(),numbers.end(),std::rand);
    cout << "sample size = " << Size << std::endl;
    int count3 = std::count_if(numbers.begin(),numbers.end(),[](int x) {return x % 3 == 0;});
    cout << "count of numbers div by 3  " << count3 << std::endl;
    
    
    int count13 = 0;
    std::for_each(numbers.begin(),numbers.end(),[&count13](int x) { count13 += x % 13 == 0 ; });
    cout << " count 13 " << count13 << std::endl;
    
    count3 = count13 = 0;
    std::for_each(numbers.begin(),numbers.end(),[&] (int x) {count3 += x % 3 == 0 ; count13 += x % 13 == 0 ;});
    cout << "count3 " << count3 << " count13 " << count13 << std::endl;
    
    return 0;
}
    

 

posted @ 2016-07-20 10:26  Commence  阅读(201)  评论(0)    收藏  举报