C++Primer 第九章课后编程题答案

//9.4
#include<iostream>
#include<vector>

using namespace std;

//查找给定值
bool find_val(vector<int>::iterator beg1, vector<int>::iterator end1, int vec)
{
	while (beg1 != end1)
	{
		if (*beg1 == vec)
			return true;
		++beg1;
	}
	return false;
}
int main()
{
	vector<int> mem{ 1,2,3,4,5,6,7,8 };
	cout << find_val(mem.begin(), mem.end(), 4) << endl;
	cout << find_val(mem.begin(), mem.end(), 9) << endl;
	return 0;
}
//9.5
#include<iostream>
#include<vector>

using namespace std;

//查找给定值
vector<int>::iterator find_val(vector<int>::iterator beg1, vector<int>::iterator end1, int vec)
{
	while (beg1 != end1)
	{
		if (*beg1 == vec)
			return beg1;
		++beg1;
	}
	return end1;
}
int main()
{
	vector<int> mem{ 1,2,3,4,5,6,7,8 };
	cout << find_val(mem.begin(), mem.end(), 4)-mem.begin() << endl;//减去mem.begin()的原因是<<运算符输出vector<int>::iterator类型的函数需要函数重载
	cout << find_val(mem.begin(), mem.end(), 9)-mem.begin() << endl;
	return 0;
}
//9.13
//创建从一个list<int>初始化vector<double>和从一个vector<int>初始化vector<double>
#include<iostream>
#include<vector>
#include<list>

using namespace std;

int main()
{
	list<int> list1 = { 1,2,3,4,5,6,7,8 };
	vector<int> v1 = {5,4,2,51,6,6,7};

	vector<double> v2(list1.begin(),list1.end());//两个迭代器 赋值
	vector<double> v3(v1.begin(), v1.end());

	cout << v2.capacity() << " " << v2.size() << " " << v2[0] << " " << v2.size() << endl;
	cout << v3.capacity() << " " << v3.size() << " " << v3[0] << " " << v3.size() << endl;
}
//9.14
//将list中的char*指针元素赋值给一个vector中的string
#include<iostream>
#include<vector>
#include<string>
#include<list>

using namespace std;

int main()
{
	list<char *> lt = {"i","am","well"};
	vector<string> str;

	str.assign(lt.begin(), lt.end());
	cout << str.capacity() << " " << str.size() << " " << str[0] << " " << str[str.size() - 1] << endl;
	return 0;
}
//9.15笨蛋方法
//判定两个vector<int>是否相等
#include<iostream>
#include<vector>


using namespace std;

int main()
{
	vector<int> v1 = { 1,2,3,4,5,6 };
	vector<int> v2 = { 1,2,3,4,7,6 };
	auto it1 = v1.begin();
	auto it2 = v2.begin();
	if (v1.size() == v2.size())
	{
		while ((it1 != v1.end()))
		{
			if (*it1 == *it2)
			{
				++it1;
				++it2;
				if(it1 == v1.end())
					cout << "相等" << endl;
			}
			else
			{
				cout << "不相等" << endl;
				break;
			}
		}
	}
	else 
		cout << "不相等" << endl;
 	return 0;
}
//9.15
//判定两个vector<int>是否相等
#include<iostream>
#include<vector>


using namespace std;

int main()
{
	vector<int> v1 = { 1,2,3,4,5,6 };
	vector<int> v2 = { 1,2,3,4,5,6 };
	v2.push_back(7);
	v2.pop_back();
	if (v1 == v2)
		cout << "相等" << endl;
	else
		cout << "不相等" << endl;
 	return 0;
}
//9.16
//判定vector<int>和list<int>是否相等
#include<iostream>
#include<vector>
#include<list>

using namespace std;

bool compare_vl(vector<int> &v, list<int> &list)
{
	auto it1 = v.begin();
	auto it2 = list.begin();
	if (v.size() == list.size())
	{
		while ((it1 != v.end()))
		{
			if (*it1 == *it2)
			{
				++it1;
				++it2;
				if (it1 == v.end())
					return true;
			}
			else
				return false;
		}
	}
	else
		return false;
}
int main()
{
	vector<int> v1 = { 1,2,3,4,5,6 };
	list<int> l1 = { 1,2,6,4,5,6 };

	if (compare_vl(v1, l1))
		cout << "相等" << endl;
	else
		cout << "不相等" << endl;
 	return 0;
}
//9.18
//从标准输入读取string序列,存入一个deque中。用迭代器输出
#include<iostream>
#include<deque>
#include<string>

using namespace std;

int main()
{
	deque<string> deq;
	string word;
	while (cin >> word)
		deq.push_back(word);
	for (auto it : deq)
		cout << it << " " << endl;
	return 0;
}
//9.19
//从标准输入读取string序列,存入一个list中。用迭代器输出
#include<iostream>
#include<list>
#include<string>

using namespace std;

int main()
{
	list<string> lt;
	string word;
	while (cin >> word)
		lt.push_back(word);
	for (auto it : lt)
		cout << it << " " << endl;
	return 0;
}
//9.20
//从list<int>拷贝元素到2个deque中,值为偶数的到一个中,值为奇数的到另一个中
#include<iostream>
#include<list>
#include<deque>

using namespace std;

int main()
{
	list<int> lt = {1,2,3,4,5,6,7,8,9}, lt1, lt2;
	deque<int> d1, d2;
	for (auto it = lt.cbegin();it != lt.end();++it)
	{
		if (*it % 2 == 0)
		{
			d1.push_back(*it);
		}
		else
			d2.push_back(*it);
	}
	//d1.insert(d1.begin(), lt1.begin(), lt1.end());
	//d2.insert(d2.begin(), lt2.begin(), lt2.end());
	cout << "偶数:";
	for (auto tem : d1)
		cout<< tem << " ";
	cout << endl << "奇数:";
	for (auto tem : d2)
		cout << tem << " ";
	return 0;
}
//9.21
//insert返回值
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main()
{
	vector<string> vec;
	string word;
	auto it = vec.begin();
	while (cin >> word)
		it = vec.insert(it, word);
	for (auto tem : vec)
		cout << tem << " ";

	return 0;
}
//9.24
//
#include<iostream>
#include<vector>

using namespace std;

int main()
{
	vector<int> vec = {1,2,3,4,5,6};
	cout << vec.at(0) << endl;
	cout << vec[1] << endl;
	cout << vec.front() << endl;
	cout << *vec.begin() << endl;

	return 0;
}
//9.26
//
#include<iostream>
#include<vector>
#include<list>

using namespace std;

int main()
{
	int ia[] = {0,1,1,2,3,5,8,13,21,55,89};
	vector<int> vec;
	list<int> lst;
	vec.assign(ia, ia + 11);
	lst.assign(ia, ia + 11);
	
	auto it1 = vec.begin();
	auto it2 = lst.begin();

	while (it1 != vec.end())
	{
		if (*it1 % 2 != 0)
		{
			it1 = vec.erase(it1);
		}
		else
			*it1++;
	}
	while (it2 != lst.end())
	{
		if (*it2 % 2 == 0)
		{
			it2 = lst.erase(it2);
		}
		else
			*it2++;
	}
	for (auto tem : vec)
	{
		cout << tem << " ";
	}
	cout << endl;
	for (auto tem : lst)
	{
		cout << tem << " ";
	}
		
	return 0;
}
//9.27
//查找并删除forward_list<int>中的奇数元素
#include<iostream>
#include<forward_list>

using namespace std;

int main()
{
	forward_list<int> flst = { 1,2,3,4,5,6,7,8,9 };
	auto prev = flst.before_begin();
	auto curr = flst.begin();

	while (curr != flst.end())
	{
		if (*curr % 2)
		{
			curr = flst.erase_after(prev);
		}
		else
		{
			prev = curr;
			++curr;
		}
	}
	for (auto tem : flst)
	{
		cout << tem << " ";
	}
}
//9.28
//查找并添加forward_list<string>
#include<iostream>
#include<string>
#include<forward_list>

using namespace std;

void find_insert_str(forward_list<string> &flst,string str1, string str2)
{
	auto curr = flst.begin();
	auto prev = flst.before_begin();
	bool state = false;
	while (curr != flst.end())
	{
		if (*curr == str1)
		{
			curr = flst.insert_after(curr, str2);
			state = true;
		}
		prev = curr;//后边顺序都改变了,要依次后移
		curr++;
	}
	if (!state)
	{
		flst.insert_after(prev,str2);
	}
}

int main()
{
	forward_list<string> flst = {"I","am","well"};
	find_insert_str(flst, "am", "very");
	for (auto tem : flst)
	{
		cout << tem << " ";
	}
	cout << endl;
	find_insert_str(flst, "a", " boy");
	for (auto tem : flst)
	{
		cout << tem << " ";
	}
}

 

//9.31
//复制奇数,删除偶数
#include<iostream>
#include<forward_list>

using namespace std;

int main()
{
	forward_list<int> flst = {0,1,2,3,4,5,6,7,8,9};
	auto curr = flst.begin();
	auto prev = flst.before_begin();
	while (curr != flst.end())
	{
		if (*curr % 2)
		{
			curr = flst.insert_after(curr, *curr);
			prev = curr;
			curr++;
		}
		else
			curr = flst.erase_after(prev);
	}
	for (auto tem : flst)
	{
		cout << tem << " ";
	}
}
//复制奇数,删除偶数
#include<iostream>
#include<list>

using namespace std;

int main()
{
	list<int> lst = {0,1,2,3,4,5,6,7,8,9};
	auto curr = lst.begin();
	while (curr != lst.end())
	{
		if (*curr % 2)
		{
			curr = lst.insert(curr, *curr);//返回的迭代器指向最新添加的元素
			curr++;
			curr++;
		}
		else
			curr = lst.erase(curr);//返回迭代器指向删除的后一个元素
	}
	for (auto tem : lst)
	{
		cout << tem << " ";
	}
}
//9.41
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main()
{
	vector<char> ch = { 'H','E','L','L','O' };
	string str(ch.data(), ch.size());

	cout << str << endl;
	return 0;
}
//9.42
#include<iostream>
#include<vector>
#include<string>

using namespace std;

void input_str(string &str)
{
	str.reserve(100);
	char ch;
	while (cin >> ch)
		str.push_back(ch);
}

int main()
{
	string str;
	input_str(str);

	cout << str << endl;
	return 0;
}
//9.43
//替换函数,使用迭代器将oldval替换为newval
#include<iostream>
#include<string>

using namespace std;

void replace_str(string &s, string oldval, string newval)
{
	auto len = oldval.size();
	if (!len)
		return;
	auto it = s.begin();
	while(it < s.end()-len)//末尾少于len的部分不用检查
	{
		auto it1 = it;
		auto it2 = oldval.begin();
		while(it2 != oldval.end() && *it1 == *it2)
		{
			it1++;
			it2++;
		}
		if (it2 == oldval.end())
		{
			it = s.erase(it, it1);
			if (newval.size())
			{
				auto it3 = newval.end();
				while (it3 > newval.begin())
				{
					it3--;
					it = s.insert(it, *it3);
				}
			}
			it += newval.size();
		}
		else
			it++;
	}
}
int main()
{
	string s = "I am a bad boy";
	replace_str(s, "bad", "good");
	cout << s << endl;

}
//9.44
//替换函数,使用下标和replace将oldval替换为newval
#include<iostream>
#include<string>

using namespace std;

void replace_str(string &s, string oldval, string newval)
{
	int p = 0;
	while ((p = s.find(oldval, p)) != string::npos)
	{
		s.replace(p, oldval.size(), newval);
		p += newval.size();
	}
}
int main()
{
	string s = "I am a bad boy";
	replace_str(s, "bad", "good");
	cout << s << endl;

}
//9.45
//使用迭代器添加名字的前缀和后缀
#include<iostream>
#include<string>

using namespace std;

void add_name(string &s, string preName, string backName)
{
	s.insert(s.begin(),1,' ');//添加的是字符不是字符串,因此要用单引号不能用双引号
	s.insert(s.begin(), preName.begin(), preName.end());
	s.append(" ");
	s.append(backName.begin(), backName.end());
}
int main()
{
	string name = "Tian";

	add_name(name,"Gu", "Le");
	cout << name << endl;

}
//9.46
//替换函数,使用迭代器添加名字的前缀和后缀
#include<iostream>
#include<string>

using namespace std;

void add_name(string &s, string preName, string backName)
{
	s.insert(0,1,' ');//添加的是字符不是字符串,因此要用单引号不能用双引号
	s.insert(0, preName);
	s.insert(s.size()," ");
	s.insert(s.size(), backName);
}
int main()
{
	string name = "Tian";

	add_name(name,"Gu", "Le");
	cout << name << endl;

}
//9.47.1
//find_first_of
#include<iostream>
#include<string>

using namespace std;

int main()
{
	string s = "ab2c3d7R4E6";
	int pos = 0;
	cout << "数字:" << endl;
	while ((pos = s.find_first_of("0123456789", pos)) != string::npos)
	{
		cout << s[pos] << " ";
		++pos;
	}
	pos = 0;
	cout << endl << "字母" << endl;
	while ((pos = s.find_first_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", pos)) != string::npos)
	{
		{
			cout << s[pos] << " ";
			++pos;
		}
	}
}
//9.47.2
//find_first_of
#include<iostream>
#include<string>

using namespace std;

int main()
{
	string s = "ab2c3d7R4E6";
	int pos = 0;
	cout << "字母:" << endl;
	while ((pos = s.find_first_not_of("0123456789", pos)) != string::npos)
	{
		cout << s[pos] << " ";
		++pos;
	}
	pos = 0;
	cout << endl << "数字" << endl;
	while ((pos = s.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", pos)) != string::npos)
	{
		{
			cout << s[pos] << " ";
			++pos;
		}
	}
}
//9.49
//输出最长既不包含上出头也不包含下出头的单词
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

void find_longest_word(ifstream &in)
{
	size_t max_length = 0;
	string longest_word,str;
	while (in >> str)//读取文件
	{
		if (str.find_first_of("bdfghjklpqty") != string::npos)
			continue;
		cout << str << " ";
		if (str.size() > max_length)
		{
			max_length = str.size();
			longest_word = str;
		}
	}
	cout << endl << "最长的字符串" << longest_word << endl;
}
int main(int argc,char *argv[])
{
	ifstream in(argv[1]);
	if (!in)
	{
		cerr << "The file open erro!" << endl;
	}
	find_longest_word(in);
	return 0;
}
//9.50.1
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main()
{
	vector<string> str = { "1","2","3","4","5","6","7","8","9" };
	int sum = 0;
	for (auto tem : str)
	{
		sum += stoi(tem);
	}
	cout << sum << endl;
}
//9.50.2
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main()
{
	vector<string> str = { "1.2","2.8","3","4" };
	double sum = 0;
	for (auto tem : str)
	{
		sum += stod(tem);
	}
	cout << sum << endl;
}
//9.51
#pragma once
#include<iostream>
#include<string>
#include<stdexcept>

using namespace std;

class date {
public:
	friend ostream &operator<<(ostream&, const date&);//重载输出运算符
	date() = default;
	date(string &ds);

	unsigned y() const { return year; }//const是函数体内数据不能改变
	unsigned m() const { return month; }
	unsigned d() const { return day; }
private:
	unsigned year, month, day;
};
//月份全称
const string month_name[] = { "January","February ","March","April","May","June","July","August","September",
                             "October","November", "December" };
//月份简写
const string month_abbr[] = { "Jan","Feb ","Mar","Apr","May","Jun","Jul","Augt","Sep","Oct","Nov", "Dec" };
//每月天数
const int days[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
inline int get_month(string &ds, int &end_of_month)
{
	int i, j;
	for (i = 0;i < 12;i++)
	{
		//检查每个字符是否与月份简写相等
		for (j = 0;j < month_abbr[i].size();j++)
			if (ds[j] != month_abbr[i][j])//不是此月的简写
				break;
		if (j == month_abbr[i].size())//与简写匹配,一直检测到最后一个字母
			break;
	}
	if (i == 12)//与所有月份都不相同
		throw invalid_argument("不是合法的月名");//抛出异常
	if (ds[j] == ' ')//空白符仅是月份简写
	{
		end_of_month = j  +  1;
		return i + 1;
	}
	for (;j < month_name[i].size();j++)
	{
		if (ds[j] != month_name[i][j])
			break;
	}
	if (j == month_name[i].size() && ds[j] == ' ')//月份全称
	{
		end_of_month = j + 1;
		return i + 1;
	}
	throw invalid_argument("不是合法的月名");//抛出异常
}
inline int get_day(string &ds, int month, int &p)
{
	size_t q;
	int day = stoi(ds.substr(p), &q);//从p开始的部分转换日期
	if (day < 1 || day > days[month])
		throw invalid_argument("不是合法日期值");
	p += q;
	return day;
}
inline int get_year(string &ds, int &p)
{
	size_t q;
	int year = stoi(ds.substr(p), &q);//从p开始的部分转换为年
	if (p + q < ds.size())
		throw invalid_argument("非法结尾内容");
	return year;
}
date::date(string &ds)
{
	int p;
	size_t q;
	if ((p = ds.find_first_of("0123456789")) == string::npos)
		throw invalid_argument("没有数字,非法日期");
	if (p > 0)
	{
		month = get_month(ds, p);
		day = get_day(ds, month, p);
		if (ds[p] != ' ' && ds[p] != ',')
			throw invalid_argument("非法间隔符");
		p++;
		year = get_year(ds, p);
	}
	else
	{
		month = stoi(ds, &q);
		p = q;
		if (month < 1 || month>12)
			throw invalid_argument("不是合法月份值");
		if (ds[p++] != '/')
			throw invalid_argument("非法间隔符");
		day = get_day(ds, month, p);
		if (ds[p++] != '/')
			throw invalid_argument("非法间隔符");
		year = get_year(ds, p);
	}
}
ostream &operator<<(ostream & out, const date &d)//重载类date的输出运算符<<
{
	out << d.y() << "年" << d.m() << "月" << d.d() << "日" << endl;
	return out;
}





#include<iostream>
#include<string>
#include"data.h"

using namespace std;

int main()
{
	string dates[] = { "Jan 1,2014","February 1 2014","3/1/2014","3,1,2014" };
	try
	{
		for (auto ds : dates)
		{
			date d1(ds);
			cout << d1;
		}
	}
	catch (invalid_argument e)
	{
		cout << e.what() << endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值