C++ Primer 课后练习10.11,10.12,10.13

本文通过C++代码示例介绍了如何使用标准库函数处理字符串,包括排序、去重及分区等操作,并展示了如何定义自定义比较器来排序自定义类型的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

课后练习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;
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值