课后练习10-11
#include<iostream>
#include<algorithm>
#include<vector>
#include<numeric>
#include<string>
using namespace std;
bool ishorter(const string &s1, const string & s2)
{
return s1.size() < s2.size();
}
void elimdups(vector<string> & words)
{
//按字典序排序
sort(words.begin(), words.end());
auto end_unique=unique(words.begin(), words.end());
words.erase(end_unique, words.end());
stable_sort(words.begin(), words.end(), ishorter);
}
int main(void)
{
vector<string> vec1 = { "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" };
for (const auto& ss : vec1)
{
cout << ss << " ";
}
cout << endl;
elimdups(vec1);
for (const auto& ss : vec1)
{
cout << ss << " ";
}
cout << endl;
return 0;
}
****************************************************************************************************************
练习10.12
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<numeric>
#include<fstream>
using namespace std;
class Sales_data
{
public:
Sales_data(string ss) :bookNo(ss){}
string isbn(){
return bookNo;
}
private:
string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
bool compareIsbn(Sales_data & s1, Sales_data & s2)
{
return s1.isbn().size() < s2.isbn().size();
}//注意const不能使用非const数据成员
int main(void)
{
ifstream is("file1.txt");
vector<string> vec;
string word;
while (is >> word)
{
vec.push_back(word);
}
Sales_data s1(vec[0]), s2(vec[1]), s3(vec[2]), s4(vec[3]), s5(vec[4]);
vector<Sales_data> vec1{ s1, s2, s3, s4, s5 };
sort(vec1.begin(), vec1.end(), compareIsbn);
for (auto & ss : vec1)
{
cout << ss.isbn() << " ";
}
}
file1
Lebron Kobe Ray Curry Westbrook
*********************************************************************************************************
*********************************************************************************************************
练习10.13
#include<iostream>
#include<algorithm>
#include<numeric>
#include<string>
#include<vector>
using namespace std;
bool oops_func(const string &ss)
{
return ss.size() >= 5;
}
int main(void)
{
vector<string> words;
string word;
while (cin >> word)
{
words.push_back(word);
}
auto iter = partition(words.begin(), words.end(), oops_func);
for (auto it = words.begin(); it != iter; ++it)
{
cout << *it << " ";
}
cout << endl;
}