国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C++ > 正文

c++ Primer Plus(第六版)第十六章習(xí)題,寫(xiě)代碼之路

2019-11-10 16:56:01
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

c++ PRimer Plus(習(xí)題16.1)

//讓用戶輸入回文的單詞,就是那種倒著讀和順著讀一樣意思的//實(shí)現(xiàn)這個(gè)功能有很多方法,用了一種簡(jiǎn)單的方法#include<iostream>#include<string>using std::string;using std ::cout;using std::cin;using std::getline;using std::endl;bool Isplalindrome(const string &s);int main(){	string p;	cout << "Enter a plalindrome Word: ";	while (getline(cin, p)&&p != "q")	{		if (Isplalindrome(p))			cout << "Yes, " << p << " is a plalindrome word!/n";		else			cout << "Sorry,is not a plalindrome word!/n";		cout << "Think about another word: (q to exit)";		//getline(cin,p);	}	cout << "Bye!/n";}bool Isplalindrome(const string &s){	string temp = s;		//string temp(words.rbegin(), words.rend());	int j = s.size();		//用上面的反轉(zhuǎn)迭代器更簡(jiǎn)單	int i=0;	for (; i <j; i++)		temp[i]=s[s.size() - i-1];			//因?yàn)閟tring索引的問(wèn)題,這里要減一個(gè)	temp[i] = '/0';	if (temp==s)		return true;	return false;}c++ Primer Plus(習(xí)題16.2)

//讓用戶輸入回文的單詞,就是那種倒著讀和順著讀一樣意思的//前面一道題目的升級(jí)版,客戶要求的//考慮輸入句子,大小寫(xiě)等復(fù)雜的情況//感覺(jué)思路不太好,結(jié)果沒(méi)什么問(wèn)題,就是饒了一點(diǎn)#include<iostream>#include<string>#include<cctype>				//處理大小寫(xiě)using std::string;using std::cout;using std::cin;using std::getline;using std::endl;bool Isplalindrome(const string &s);int main(){	string p;	cout << "Enter a plalindrome word: ";	while (getline(cin, p) && p != "q")	{		if (Isplalindrome(p))			cout << "Yes, " << p << " is a plalindrome./n";		else			cout << "Sorry,is not a plalindrome./n";		cout << "Think about another word: (q to exit)";		//getline(cin,p);	}	cout << "Bye!/n";}bool Isplalindrome(const string &s){	string temp;		//這個(gè)用于存儲(chǔ)去掉大寫(xiě),和非字母字符的string類,反轉(zhuǎn)后的類				int i = 0;	int j = s.size() - 1;	for (; j>=0;j--)	{		if (isalpha(s[j]))					//判斷字符是否是字母			{								//處理大小寫(xiě)字符			temp.push_back(tolower(s[j]));	//還是這種方法好一點(diǎn)			i++;		}}	//temp[i] = '/0'; string的結(jié)尾標(biāo)記沒(méi)有規(guī)定是'/0'這種方法不可行	string tem(temp.rbegin(), temp.rend());	if (temp == tem)		return true;	return false;}c++ Primer Plus(習(xí)題16.3)

//這題是修改程序清單16.3,改成從文件中讀取單詞,而不是從數(shù)組中 //書(shū)上已經(jīng)有解決方案了,照著就ok.#include <iostream>  #include <fstream>  #include <vector>  #include <string>  #include <cstdlib>  #include <ctime>  #include <cctype>  const int NUM = 26;void Readword();std::vector<std::string> input;			//全局變量省的傳遞參數(shù)了int main(){	std::srand(std::time(0)); 	char play;	std::cout << "Will you play a word game? <Y/N> ";	std::cin >> play;	play = std::tolower(play);	Readword();	while (play=='y')	{		std::string target= input[std::rand() % NUM];		int length = target.length();		std::string attempt(length, '-');		std::string badchars;		int guesses = 6;		std::cout << "Guess my secret word. It has " << length 			<< " letters, and you guess/n" << "one letter at a time. You get " 			<< guesses << " wrong guesses./n";		std::cout << "Your word: " << attempt << std::endl;		while (guesses > 0 && attempt != target)		{			char letter;			std::cout << "Guess a letter: ";			std::cin >> letter;			if ((badchars.find(letter) != std::string::npos) //nops是string中的最大存儲(chǔ)字符數(shù)				|| (attempt.find(letter)!= std::string::npos))			{				std::cout << "You already guessed that. Try again./n";				continue;			}			int loc = target.find(letter);			//記錄找到字符的位置			if (loc == std::string::npos)			{				std::cout << "Oh, bad guess!/n";				--guesses;				badchars +=letter;					//記錄到錯(cuò)誤的那里			}			else			{				std::cout << "Good guess!/n";				attempt[loc] =letter;		//顯示猜對(duì)的字符				loc = target.find(letter, loc + 1);				while (loc != std::string::npos)	//顯示這個(gè)單詞后面相同的字符				{					attempt[loc] =letter;					loc = target.find(letter, loc + 1);				}			}			std::cout << "Your word: " << attempt << std::endl;			if (attempt != target)			{				if (badchars.length() > 0)					std::cout << "Bad choices: " << badchars << std::endl;				std::cout << guesses << " bad guesses left/n";			}		}		if (guesses > 0)			std::cout << "That's right/n";		else			std::cout << "Sorry, the word is " << target << "./n";		std::cout << "Will you play another? <Y/N> ";		std::cin >> play;		play = tolower(play);	}	std::cout << "Bye!/n";	return 0;}void Readword(){	std::ifstream fin;	fin.open("data.txt");	if(!fin.is_open())	{		std::cout << "Open file data.txt error!/n";		exit(EXIT_FAILURE);	}	std::string s;				//存儲(chǔ)讀取的單詞	while (!fin.eof())	{		fin>>s;		input.push_back(s);			//動(dòng)態(tài)增加input的成員數(shù)量	}	fin.close();}c++ Primer Plus(習(xí)題16.4)

//這題是熟悉stl特性,編寫(xiě)一個(gè)函數(shù)接受一個(gè)數(shù)組和元數(shù)個(gè)數(shù)//對(duì)數(shù)組進(jìn)行排序,刪除重復(fù)的值,并返回最終的元素個(gè)數(shù)//考慮到壓縮元素,可以使用list模板類,書(shū)上的unique()函數(shù)也是一種提示#include<iostream>#include<list>							//list模板,雙向鏈表#include<algorithm>						//迭代器std::list<long>f;int reduce(long ar[], int i);void outlong(long n) { std::cout << n << " "; }int main(){	using std::cout;	long test[12] = { 40,51,57,89,87,85,40,40,51,64,52,0 };	int result;	result = reduce(test, 12);	cout << "Source array: /n";	for (long x : test)					//基于范圍的for循環(huán)			cout << x << " ";	cout << "/nThe mount: " << 12;	std::cout << "/nAfter sort and remove, the number is "<<result<<std::endl;	cout << "After that: /n";	std::for_each(f.begin(), f.end(), outlong);	std::cout << "Bye!/n";	return 0;}int reduce(long ar[], int i)			//使用迭代器將非常其簡(jiǎn)單,不過(guò)要會(huì)choose{	f.insert(f.begin(),ar, ar + i);	f.sort();						//排序	f.unique();						//壓縮相同的元素	return f.size();}c++ Primer Plus(習(xí)題16.5)

//這題是上一題的泛型,可以不依賴于特定的數(shù)組類型//這就是迭代器的終極奧義,獨(dú)立于類型#include<iostream>#include<algorithm>#include<string>#include<list>	template<class T>int reduce(T ar[], int n);template<class T>void outlong(T n) { std::cout << n << " "; }int main(){	using std::cout;	cout << "Test a function,accept a type array and longth,return after reduce same elemet"		"mount." << std::endl;	long test[12] = { 40,51,57,89,87,85,40,40,51,64,52,0 };	int result;	result = reduce(test, 12);	cout << result<<std::endl;std::string tests[5] = { "i","m a C","+","+","student." };	result = reduce(tests, 5);	cout << result<<std::endl;}template<class T>int reduce(T ar[], int n){	std::list<T>f;	f.insert(f.begin(), ar, ar + n);	f.sort();	f.unique();	std::cout << "After reduce and sort:/n";	std::for_each(f.begin(), f.end(), outlong<T>);	std::cout << std::endl;	return f.size();	}c++ Primer Plus(習(xí)題16.6)

//改寫(xiě)程序清單12.12就是那個(gè)排隊(duì)買東西的,在c primer中也有//使用stl queue 有高級(jí)的函數(shù)輔助加上一些queue 的stl功能,//很容易實(shí)現(xiàn),畢竟是標(biāo)準(zhǔn)的,我們自己做的功能沒(méi)那么強(qiáng)大#include <iostream>  #include <cstdlib>  #include <ctime>  #include <queue>class Customer{private:	long arrive;	int processtime;public:	Customer() { arrive = processtime = 0; }	void set(long when) 	{		processtime = std::rand() % 3 + 1;		arrive = when;	}	long when()const { return arrive; }	int ptime()const { return processtime; }};typedef Customer Item;const int MIN_PER_HR = 60;bool newcustomer(double x);int main(){	using namespace std;	srand(time(0));	cout << "Case Study: Bank of Heather Automatic Teller/n";	cout << "Enter maximum size of queue: ";		//最大的排隊(duì)人數(shù)	int qs;	cin >> qs;	queue <Item>line;								//queue本人沒(méi)看到指定隊(duì)列數(shù)的構(gòu)造函數(shù)	cout << "Enter the number of simulation hours: ";	//測(cè)試的時(shí)間	int hours;	cin >> hours;	long cyclelimit = MIN_PER_HR*hours;	cout << "Enter the average number of cunstomers per hour: ";	//每小時(shí)的額客戶數(shù)	double perhour;	cin >> perhour;	double min_per_cust;	min_per_cust = MIN_PER_HR / perhour;				//記錄總的分鐘數(shù)	Item temp;	long turnaways = 0;									//拒絕人數(shù)	long customers = 0;									//來(lái)的人數(shù)	long served = 0;									//服務(wù)人數(shù)	long sum_line = 0;									//隊(duì)列的長(zhǎng)度	int wait_time = 0;									//取款機(jī)空閑的等待時(shí)間		long line_wait = 0;									//隊(duì)列的總等待時(shí)間	for (long cycle = 0; cycle < cyclelimit; cycle++)	{		if (newcustomer(min_per_cust))		{			if (line.size()==qs)						//檢查隊(duì)列的長(zhǎng)度是否等于最大排隊(duì)人數(shù)				turnaways++;			else 			{				customers++;				temp.set(cycle);				line.push(temp);							//enqueue和push同樣的方法			}		}		if (wait_time <= 0 && !line.empty())		{			line.pop();								//彈出,不需要item參數(shù)			wait_time = temp.ptime();				line_wait += cycle - temp.when();			served++;		}		if (wait_time > 0)			wait_time--;		sum_line += (line.size()) / 2;	}	if (customers > 0) {		cout << "customers accepted: " << customers << endl;		cout << "  customers served: " << served << endl;		cout << "        turnaways: " << turnaways << endl;		cout << "average queue size: ";		cout.precision(2);		cout.setf(ios_base::fixed, ios_base::floatfield);		cout << (double)sum_line / cyclelimit << endl;		cout << "average wait time: " << (double)line_wait / served << " minutes/n";	}	else		cout << "No customers!/n";	cout << "Done!/n";	return 0;}bool newcustomer(double x){	return (rand()*x / RAND_MAX < 1);}c++ Primer Plus(習(xí)題16.7)

//一個(gè)彩票卡的游戲,本人沒(méi)聽(tīng)說(shuō)過(guò),//也是設(shè)計(jì)一個(gè)函數(shù),要求使用vector容器//額,程序每次運(yùn)行獲取的值都一樣,這要是真是中獎(jiǎng)的程序,等著罵吧#include<iostream>#include<vector>#include<algorithm>using namespace std;vector<int> Lotto(int count, int ccount);	//返回一個(gè)包含vector										//從第一個(gè)參數(shù)隨機(jī)選擇第二個(gè)參數(shù)數(shù)量值的對(duì)象int main(){	cout << "This is a Lottery card Test program."		"To test a funtion Lotto: /n";	vector<int>winners;	int numb, times;	cout << "Enter a draw range: ";	cin >> numb;	cout << "How many times your draw less than: ";	cin >> times;	winners = Lotto(numb,times);	cout<< "The winners Lottery card winning number is:/n";	for (auto m = winners.begin(); m != winners.end(); m++)    //用迭代器的方式輸出容器對(duì)象的值	{		cout<< *m << endl;	}	cout << "Good lucky!/n";	cout << "Test complete!/n";	return 0;}vector<int> Lotto(int count, int ccount){	vector<int>pvalue(count);				//用來(lái)記錄可能值,用了指定元素個(gè)數(shù)的f方法	vector<int>value;						//用于返回	for (int i = 0; i < count; i++)		pvalue[i] = i + 1;	for (int i = 0; i < ccount; i++)				//打亂ccount指定的次數(shù),每次取第一個(gè)值存入數(shù)組	{		random_shuffle(pvalue.begin(), pvalue.end());		value.push_back(pvalue[0]);	}	return value;}c++ Primer Plus(習(xí)題16.8)

//兩個(gè)朋友認(rèn)識(shí)的人的名字,用容器存儲(chǔ)//合并兩個(gè)人中相同的元素,保存到第三個(gè)容器中//考慮采用set關(guān)聯(lián)容器#include<iostream>#include<string>#include<set>#include<algorithm>#include<iterator>				//迭代器的頭文件int main(){	using namespace std;	ostream_iterator<string, char>out(cout, " ");			//輸出迭代器	string Mat[5] = { "Joly","Jack","Zoe","Jay,Zou","X" };	//直接用這個(gè)來(lái)初始化了	string Pat[4] = { "Joly","Emil","X","Lai Mei" };	set<string>A(Mat, Mat + 5);			//第一個(gè)容器,set容器自動(dòng)排序,大家都知道	cout << "Mat's friends:/n";	copy(A.begin(), A.end(), out);		//STL函數(shù),復(fù)制到輸出流迭代器	cout << endl;						//說(shuō)白了,就是顯示容器內(nèi)容	set<string>B(Pat, Pat + 4);	cout << "Pat's friends:/n";	copy(B.begin(), B.end(), out);	cout << endl;	set<string>C;	set_union(A.begin(), A.end(), B.begin(), B.end(), 		insert_iterator<set<string>>(C, C.begin()));		//AB集合,用了一個(gè)插入迭代器	cout << "Friends they have:/n";	copy(C.begin(), C.end(), out);	cout << endl;	return 0;}c++ Primer Plus(習(xí)題16.9)

//這是作者的一個(gè)假設(shè),在我們生活中也有很多這樣的假設(shè)//他的思路是在數(shù)組中排序元素,然后復(fù)制到鏈表中(因?yàn)殒湵砼判蚴窃诤苈闊?/借用中間容器實(shí)現(xiàn)排序功能的實(shí)現(xiàn),下面就是測(cè)試時(shí)間#include<iostream>#include<vector>#include<list>#include<algorithm>#include<iterator>#include<ctime>					//提供時(shí)間函數(shù)const int Num=1000000;			//這個(gè)要足夠大void outint(int n) { std::cout << n << " "; }int main(){	using namespace std;	vector<int>vi0(Num);				//指定個(gè)數(shù)的初始化	for (int i=0; i < Num; i++)		vi0[i]=rand()%100 + 1;	cout << "Hello,this program set to accumulate time between STL sort method "		"for vector object,and list sort methods./n";	cout << "Number of elements is " << Num << endl;	vector<int>vi;	vi = vi0;										//調(diào)用vector的賦值運(yùn)算符	list<int>li(Num);								//指定個(gè)數(shù)的初始化	copy(vi0.begin(), vi0.end(), li.begin());		//不同容器之間的數(shù)據(jù)復(fù)制	//計(jì)算三種方法的時(shí)間,方法一,使用使用STL算法對(duì)vi進(jìn)行排序	clock_t start = clock();	sort(vi.begin(), vi.end());	clock_t end = clock();	cout << "Frist method,using STL sort time " << (double)(end - start) / CLOCKS_PER_SEC << " s./n";	//第二次測(cè)試	clock_t start_2= clock();	li.sort();	clock_t end_2= clock();	cout << "Second method,using list sort time " << (double)(end_2 - start_2) / CLOCKS_PER_SEC << " s./n";	//第三次測(cè)試	copy(vi0.begin(), vi0.end(), li.begin());		//重置li鏈表	clock_t start_3 = clock();	copy(li.begin(), li.end(), vi.begin());			//把list的值復(fù)制到vi容器	sort(vi.begin(), vi.end());						//排序	copy(vi.begin(), vi.end(), li.begin());	clock_t end_3 = clock();	cout << "Third method,using other sort time " << (double)(end_3 - start_3) / CLOCKS_PER_SEC << " s./n";	cout << "Now,you can see,/nwhen list container count become big,sortting them is too long."		"/nSo,make right choice to compelete a function./n";	return 0;}c++ Primer Plus(習(xí)題16.10)

//又是修改程序的題目,這最后的習(xí)題涉及到智能指針//然后我們要做的就是滿足客戶的額要求,升級(jí)我們的程序//不知道加了哪個(gè)頭文件導(dǎo)致cout不明確//這題的思路是書(shū)上的方案,如果自己做的話可以想排序字符串那樣//只使用指針數(shù)組排序,對(duì)指針進(jìn)行排序#include<iostream>#include<string>#include<vector>#include<algorithm>				//提供一些STL方法#include<memory>				//智能指針頭文件struct Review					//結(jié)構(gòu)是一種默認(rèn)為公有的類{	std::string title;	int rating;	double price;				//增加的成員,書(shū)價(jià)格};using namespace std;		//書(shū)上也是按引用傳遞指針的意義非凡,其實(shí)不還是指針,沒(méi)設(shè)呢么區(qū)別bool Operator<(shared_ptr<Review>r1, shared_ptr<Review>r2);//按字母排序的bool woreThan(shared_ptr<Review>r1, shared_ptr<Review>r2);	//評(píng)分排序的bool expensivethen(shared_ptr<Review>r1, shared_ptr<Review>r2);	//價(jià)格排序的bool FillReview(Review*rr);void ShowReview(shared_ptr<Review>rr);			//有點(diǎn)特別,書(shū)上的用法void Showmenu();int main(){	Review temp;	vector<shared_ptr<Review>>pr;	while (FillReview(&temp))		pr.push_back(shared_ptr<Review>(new Review(temp)));	//沒(méi)認(rèn)真看書(shū),這個(gè)初始化想了好久好久	vector<shared_ptr<Review>>tem(pr);		//用vector自帶的初始化,是一個(gè)按名稱排序的vector	sort(tem.begin(), tem.end());			//創(chuàng)建按指針排序的<運(yùn)算符,全排序	//按評(píng)分排序的	vector<shared_ptr<Review>>tem2(pr);	sort(tem2.begin(), tem2.end(), woreThan);		//調(diào)用函數(shù)進(jìn)行排序,完整弱排序	//按價(jià)格排序	vector<shared_ptr<Review>>tem3(pr);	sort(tem3.begin(), tem3.end(), expensivethen);	if (pr.size() > 0)	{		std::cout<< "Thank you,You entered the following "			<< pr.size() << " ratings./n";		Showmenu();		char choose;		cin >> choose;		while (choose != 'q')		{			switch (choose)			{					//天真的我竟然在后面加&這個(gè)			case 'a':for_each(pr.begin(),pr.end(), ShowReview); break;			case'b': for_each(tem.begin(),tem.end(), ShowReview); break;			case'c':for_each(tem2.begin(), tem2.end(), ShowReview); break;			case'd':for_each(tem2.rbegin(), tem2.rend(), ShowReview); break;			case 'e':for_each(tem3.begin(), tem3.end(), ShowReview); break;			case'f':for_each(tem3.rbegin(), tem3.rend(), ShowReview); break;			case 'q':break;			default: std::cout << "Error choose,choose again:/n";				break;			}			Showmenu();			cin >> choose;		}	}	else		std::cout << "No data!/n";	std::cout << "Bye!/n";	return 0;}bool operator<(shared_ptr<Review>r1, shared_ptr<Review>r2)		{	if (r1->title < r2->title)		return true;	else if (r1->title == r2->title&&r1->rating < r2->rating)		return true;		//這里不想太麻煩,就選擇評(píng)分為優(yōu)先排序項(xiàng)目	else		return false;}bool woreThan(shared_ptr<Review>r1, shared_ptr<Review>r2)  //按評(píng)分升序{	if (r1->rating<r2->rating)		return true;	else		return false;}bool expensivethen(shared_ptr<Review>r1, shared_ptr<Review>r2) //按價(jià)格升序{	if (r1->price < r2->price)		return true;	else		return false;}bool FillReview(Review*rr){	std::cout << "Enter book title(quit to quit): ";	std::getline(std::cin, rr->title);	if (rr->title == "quit")		return false;	std::cout << "Enter book rating: ";	std::cin >> rr->rating;	if (!std::cin)		return false;					//檢查錯(cuò)誤輸入	std::cout << "Enter book price(unit:yuan): ";	std::cin >> rr->price;	if (!std::cin)		return false;	while (std::cin.get() != '/n')		continue;	return true;}void ShowReview(shared_ptr<Review>rr){	std::cout << rr->title<< "/t/t/t/t/t" << rr->rating << "/t $ " << rr->price 		<< "/tyuan./n";}void Showmenu(){	std::cout << "Make a choose to display them: /n"		"a) Display by original order.            b) Display by alphabetic order./n"		"c) Display by rating ascending order.     d) Display by rating descending order./n"		"e) Display by price ascending order.      f) Display by price descending order./n"		"q) quit./n";}


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 许昌县| 奈曼旗| 同江市| 新泰市| 新化县| 墨玉县| 崇文区| 罗江县| 渭南市| 林西县| 台中县| 同心县| 西吉县| 康保县| 景德镇市| 蓝山县| 高密市| 侯马市| 尖扎县| 新建县| 宾川县| 来安县| 崇信县| 广饶县| 嘉定区| 临沂市| 永仁县| 蕉岭县| 上杭县| 淮北市| 吴江市| 阿拉善左旗| 金乡县| 株洲市| 临武县| 滕州市| 将乐县| 阿拉善左旗| 崇义县| 吕梁市| 凤翔县|