lambda与函数调用的转换

14.38 编写一个类令其检查某个给定的string对象的长度是否与一个阈值相等。使用该对象编写程序,统计并报告在输入的文件中长度为1的单词有多少个,长度为2的单词有多少个、.....、长度为10的单词又有多少个。

#include<iostream>

#include<vector>

#include<string>

#include<algorithm>

#include<fstream>

using namespace std;



class Length

{

public:

    Length(size_t n):sz(n) {}

    bool operator()(string &s){ return s.size()==sz;}

private:

    size_t sz;

};



int main()

{

    ifstream in("4.txt");

    string str;

    vector<string> vec;

    int arr[10];

    while(in>>str)

        vec.push_back(str);

    for(size_t i=0;i<10;++i)

        arr[i]=count_if(vec.begin(),vec.end(),Length(i+1));

    for(size_t i=0;i<10;++i)

        cout<<arr[i]<<" ";

    cout<<endl;

    return 0;

}

 

你可能感兴趣的:(lambda)