c++primer练习10.19-10.25

练习10.19

用stable_partition重写前一题的程序,与stable_sort类似,在划分后的序列中维持原有元素的顺序

void biggies(vector<string> &a,vector<string>::size_type sz)
{
    elimDups(a);
    stable_sort(a.begin(),a.end(),
    [](const string &a,const string&b)
    {return a.size()<b.size();});

    auto lar=stable_partition(a.begin(),a.end(),
    [sz](string &a)
    {return a.size()>=sz;});
    auto count=a.end()-lar;
    cout<<count<<" "<<make_plural(count,"word","s")<<"of length"<<sz<<"or longer"<<endl;
    for_each(lar,a.end(),
    [](const string&a)
    {cout<<a<<" ";});
    cout<<endl;
}

练习10.20

标准库定义了一个名为count_if的算法。类似find_if。重写统计长度超过6的部分

vector<string> a{"beauty","beauty","yeah"};int sz=4;
int d=count_if(a.begin(),a.end(),[sz](string &a)->bool{if(a.size()>sz)return true;return false;});
cout<<d<<endl;

练习10.21

编写一个lambda,捕获一个局部int变量,并递减变量值,直至它变为0.一旦变量为0.再调用lambda应该不再递减变量。lambda应该返回一个bool值,指出捕获的变量是否为0

int num=9;
auto f=[num](void)mutable->bool{while(num!=0)--num;if(num==0)return true;return false;};
cout<<f()<<endl;

练习10.22

重写统计长度小于等于6的单词数量的程序

vector<string> a{"beauty","beauty","yeah"};int sz=6;
int d=count_if(a.begin(),a.end(),bind(shorter,_1,sz));
cout<<d<<endl;

练习10.23

bind接受几个参数

::1+x,第一个是可调用对象,x个参数

练习10.24

给定一个string,使用bind和check_size在一个int的vector中查找一个大于string长度的值

vector<int> a{2,1,3,4,5,6,1};
string b = "happy";
auto d=find_if(a.begin(),a.end(),bind(check_size,b,_1));
cout<<*d<<endl;

练习10.25

使用check_size和bind重写biggies函数

bool check_size(const string &s, string::size_type sz)
{
    return s.size() < sz;
}

void biggies(vector<string> &a,vector<string>::size_type sz)
{auto check = bind(check_size,_1,sz);}

 

posted @ 2022-07-22 19:02  yddl  阅读(21)  评论(0编辑  收藏  举报