您的位置:首页 > 其它

10.3.1节练习

2016-06-03 20:10 337 查看
练习10.11 编写程序,使用stable_sort和isShort将传递给你的elimDups版本的vector排序。打印vector的内容,验证你的程序的正确性。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void elimDups(vector<string> &);
bool isShort(const string &, const string &);
int main()
{
string word;
vector<string> text;
while (cin >> word) {
text.push_back(word);
}
elimDups(text);
stable_sort(text.begin(), text.end(), isShort);
for (auto i : text) {
cout << i << " ";
}
cout << endl;
return 0;

}
void elimDups(vector<string> &text)
{
sort(text.begin(), text.end());
auto iter = unique(text.begin(), text.end());
text.erase(iter, text.end());
}
bool isShort(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}


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

(换了硬盘没备份。。。 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 isFive(const string &);
int main()
{
vector<string> text;
string word;
while (cin >> word) {
text.push_back(word);
}
auto iter = partition(text.begin(), text.end(), isFive);
for (auto beg = text.begin(); beg != iter; ++beg) {
cout << *beg << " ";
}

cout << endl;
return 0;
}
bool isFive(const string &s)
{
return s.size() >= 5;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: