第十章 10.2.3节练习 & 10.3.1节练习

来源:互联网 发布:站长工具 js格式化 编辑:程序博客网 时间:2024/05/17 02:17

练习10.9:

实现你自己的elimDups。测试你的程序,分别在读取输入后、调用unique后及调用erase后打印vector的内容。

解答:

恩,书上已经实现了一个。就不在去累述了。

如果让我去实现,我感觉unique还是比较麻烦的,我会选用set容器去做除重的工作。


练习10.10:

你认为算法不改变容器大小的原因是什么?

解答:

算法,就是计算方法而已。其本意很明确,只是单纯的做计算,而不去改变参与运算元素个数。

如果,一个算法在计算过程中,参与运算的原始元素个数是动态的,这个算法就应该是不可控的。

不可控的算法对于我们来说,就是无用的算法。

为了保证算法的单纯作用,它是不能改变容器大小的,也就是参与运算的元素个数。


练习10.11:

编写程序,使用stable_sort和isShort将传递给你的elimDups版本的vector排序。打印vector的内容,验证你的程序的正确性。

解答:

#include <iostream>#include <algorithm>#include <vector>#include <list>#include <iterator>#include <string>using namespace std;bool isShorter(const string &s1, const string &s2){return s1.size() < s2.size();}void elimDups(vector<string> words){sort(words.begin(), words.end(), isShorter);auto end_unique = unique(words.begin(), words.end());words.erase(end_unique, words.end());for (auto i : words){cout << i << " ";}cout << endl;}int main(){vector<string> svec{ "apple", "pear", "hello", "world" };elimDups(svec);stable_sort(svec.begin(), svec.end(), isShorter);for (const auto &s : svec){cout << s << " ";}cout << endl;}

练习10.12:

编写名为compareIsbn的函数,比较两个Sales_data对象的isbn()成员。使用这个函数排序一个保存Sales_data对象的vector。

解答:

这个其实和上面的代码是一样的,不过是将string替换成Sales_data结构体。将isShorter改写成比较isbn()成员。

这里,懒得去查Sales_data的结构体了,代码就略过吧。


练习10.13:

标准库定义了名为partition的算法,它接受一个谓词,对容器内容进行划分,使得谓词为true的值会排在容器的前半部分,而使谓词为false的值会排在后半部分。

算法返回一个迭代器,指向最后一个是谓词为true的元素之后的位置。编写函数,接受一个string,返回一个bool值,指出string是否有5个或更多字符。使用此函数划分words。打印出长度大于等于5的元素。

解答:

#include <iostream>#include <algorithm>#include <vector>#include <string>using namespace std;bool larger5(const string& str){return str.size() >= 5;}int main(){vector<string> svec{ "a","ac","apple", "pear", "hell", "world", "watermelon", "baidu", "google" };vector<string>::iterator bound;bound = partition(svec.begin(), svec.end(), larger5);for (auto it = svec.cbegin(); it != bound; ++it){cout << *it << " ";}cout << endl;}

这里的谓词指的就是一个返回bool值的函数,用来做出判断的。

理解这个词,代码马上就能写出来了。

0 0
原创粉丝点击