您的位置:首页 > 编程语言 > C语言/C++

C++Primer 10.3.2节练习 10.14题 10.15题 10.16题 10.17题 10.18题 10.19题

2017-12-31 23:38 525 查看
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
#include<iterator>
#include<string>
#include<functional>  //bind函数和std::placeholders命名空间
#include<fstream>
#include<numeric>
using namespace std;//来自所有std的名字都可以在我们的程序中使用
using namespace std::placeholders;int
//练习10.15
lambdaAdd(int a)
{//利用lambda表达式进行加法运算
auto result=[a](const int b) {return a + b; };
return result(100);
}
//练习10.16
void biggies(vector<string>&words, vector<string>::size_type sz)
{
elimDups(words);//将word按字典序排序,删除重复单词
//按照长度排序,长度相同的单词维持字典序
stable_sort(words.begin(), words.end(), [](const string &a, const string&b) {return a.size() < b.size(); });
//获取一个迭代器,指向第一个满足size()>=sz的元素
auto wc = find_if(words.begin(), words.end(), [sz](const string&s) {return s.size() >= sz; });
//计算满足size>=sz的元素的数目
auto count = words.end() - wc;
cout << count << " " << make_plural(count, "word", "s") <<
" of length " << sz << " or longer" << endl;
//打印长度大于等于给定值的单词,每个单词后面接一个空格
for_each(wc, words.end(), [](const string &s) {cout << s << " "; });
cout << endl;
}
//练习10.18
void biggies1(vector<string>&words, vector<string>::size_type sz)
{//利用partition算法重写biggies
elimDups(words);
//按照长度排序,长度相同的单词维持字典序
stable_sort(words.begin(), words.end(), [](const string &a, const string&b) {return a.size() < b.size(); });
//获取一个迭代器,指向第一个满足size()>=sz的元素
auto wc = partition(words.begin(), words.end(), [sz](const string&s) {return s.size()<sz; });
//计算满足size>=sz的元素的数目
auto count = words.end()-wc;
cout << count << " " << make_plural(count, "word", "s") <<
" of length " << sz << " or longer" << endl;
//打印长度大于等于给定值的单词,每个单词后面接一个空格
for_each(wc,words.end(), [](const string &s) {cout << s << " "; });
cout << endl;
}
练习19
void biggies2(vector<string>&words, vector<string>::size_type sz)
{//使用stable_partition重写biggies2
elimDups(words);//将word按字典序排序,删除重复单词
//划分长度,长度相同的单词维持字典序
auto wc=stable_partition(words.begin(), words.end(), [sz](const string &s) {return s.size() < sz; });//注意这里是小于,不然会出现逆序的情况
//计算满足size>=sz的元素的数目
auto count = words.end() - wc;
cout << count << " " << make_plural(count, "word", "s") <<
" of length " << sz << " or longer" << endl;
//打印长度大于等于给定值的单词,每个单词后面接一个空格
for_each(wc, words.end(), [](const string &s) {cout << s << " "; });
cout << endl;
}
int main()
{
//测试10.14
auto result = [](int a, int b) {return a+ b; };
cout << result(1, 2) << endl;
//测试练习10.15
cout << lambdaAdd(20)<< endl;
//测试练习10.16 biggies
vector<string> words = { "comouter","am","cmazyaa","day","biology","man","intelligence","yeah" };
biggies(words, 5);
}
//测试练习10.17 重写类成员排序算法,利用lambda表达式
sort(vSa.begin(), vSa.end(),[](Sales& sa1,Sales& sa2){return sa1.isbn().size() < sa2.isbn().size();});
for_each(vSa.begin(), vSa.end(), [](Sales&sa) {cout << sa.isbn() << ' '; });
cout << endl;
//测试练习18和练习19
biggies1(words,5);
biggies2(words, 5);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐