c++ PRimer Plus(習題16.1)
//讓用戶輸入回文的單詞,就是那種倒著讀和順著讀一樣意思的//實現這個功能有很多方法,用了一種簡單的方法#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(); //用上面的反轉迭代器更簡單 int i=0; for (; i <j; i++) temp[i]=s[s.size() - i-1]; //因為string索引的問題,這里要減一個 temp[i] = '/0'; if (temp==s) return true; return false;}c++ Primer Plus(習題16.2)//讓用戶輸入回文的單詞,就是那種倒著讀和順著讀一樣意思的//前面一道題目的升級版,客戶要求的//考慮輸入句子,大小寫等復雜的情況//感覺思路不太好,結果沒什么問題,就是饒了一點#include<iostream>#include<string>#include<cctype> //處理大小寫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; //這個用于存儲去掉大寫,和非字母字符的string類,反轉后的類 int i = 0; int j = s.size() - 1; for (; j>=0;j--) { if (isalpha(s[j])) //判斷字符是否是字母 { //處理大小寫字符 temp.push_back(tolower(s[j])); //還是這種方法好一點 i++; }} //temp[i] = '/0'; string的結尾標記沒有規定是'/0'這種方法不可行 string tem(temp.rbegin(), temp.rend()); if (temp == tem) return true; return false;}c++ Primer Plus(習題16.3)//這題是修改程序清單16.3,改成從文件中讀取單詞,而不是從數組中 //書上已經有解決方案了,照著就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; //全局變量省的傳遞參數了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中的最大存儲字符數 || (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; //記錄到錯誤的那里 } else { std::cout << "Good guess!/n"; attempt[loc] =letter; //顯示猜對的字符 loc = target.find(letter, loc + 1); while (loc != std::string::npos) //顯示這個單詞后面相同的字符 { 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; //存儲讀取的單詞 while (!fin.eof()) { fin>>s; input.push_back(s); //動態增加input的成員數量 } fin.close();}c++ Primer Plus(習題16.4)//這題是熟悉stl特性,編寫一個函數接受一個數組和元數個數//對數組進行排序,刪除重復的值,并返回最終的元素個數//考慮到壓縮元素,可以使用list模板類,書上的unique()函數也是一種提示#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循環 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) //使用迭代器將非常其簡單,不過要會choose{ f.insert(f.begin(),ar, ar + i); f.sort(); //排序 f.unique(); //壓縮相同的元素 return f.size();}c++ Primer Plus(習題16.5)//這題是上一題的泛型,可以不依賴于特定的數組類型//這就是迭代器的終極奧義,獨立于類型#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(習題16.6)//改寫程序清單12.12就是那個排隊買東西的,在c primer中也有//使用stl queue 有高級的函數輔助加上一些queue 的stl功能,//很容易實現,畢竟是標準的,我們自己做的功能沒那么強大#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: "; //最大的排隊人數 int qs; cin >> qs; queue <Item>line; //queue本人沒看到指定隊列數的構造函數 cout << "Enter the number of simulation hours: "; //測試的時間 int hours; cin >> hours; long cyclelimit = MIN_PER_HR*hours; cout << "Enter the average number of cunstomers per hour: "; //每小時的額客戶數 double perhour; cin >> perhour; double min_per_cust; min_per_cust = MIN_PER_HR / perhour; //記錄總的分鐘數 Item temp; long turnaways = 0; //拒絕人數 long customers = 0; //來的人數 long served = 0; //服務人數 long sum_line = 0; //隊列的長度 int wait_time = 0; //取款機空閑的等待時間 long line_wait = 0; //隊列的總等待時間 for (long cycle = 0; cycle < cyclelimit; cycle++) { if (newcustomer(min_per_cust)) { if (line.size()==qs) //檢查隊列的長度是否等于最大排隊人數 turnaways++; else { customers++; temp.set(cycle); line.push(temp); //enqueue和push同樣的方法 } } if (wait_time <= 0 && !line.empty()) { line.pop(); //彈出,不需要item參數 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(習題16.7)//一個彩票卡的游戲,本人沒聽說過,//也是設計一個函數,要求使用vector容器//額,程序每次運行獲取的值都一樣,這要是真是中獎的程序,等著罵吧#include<iostream>#include<vector>#include<algorithm>using namespace std;vector<int> Lotto(int count, int ccount); //返回一個包含vector //從第一個參數隨機選擇第二個參數數量值的對象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++) //用迭代器的方式輸出容器對象的值 { cout<< *m << endl; } cout << "Good lucky!/n"; cout << "Test complete!/n"; return 0;}vector<int> Lotto(int count, int ccount){ vector<int>pvalue(count); //用來記錄可能值,用了指定元素個數的f方法 vector<int>value; //用于返回 for (int i = 0; i < count; i++) pvalue[i] = i + 1; for (int i = 0; i < ccount; i++) //打亂ccount指定的次數,每次取第一個值存入數組 { random_shuffle(pvalue.begin(), pvalue.end()); value.push_back(pvalue[0]); } return value;}c++ Primer Plus(習題16.8)//兩個朋友認識的人的名字,用容器存儲//合并兩個人中相同的元素,保存到第三個容器中//考慮采用set關聯容器#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" }; //直接用這個來初始化了 string Pat[4] = { "Joly","Emil","X","Lai Mei" }; set<string>A(Mat, Mat + 5); //第一個容器,set容器自動排序,大家都知道 cout << "Mat's friends:/n"; copy(A.begin(), A.end(), out); //STL函數,復制到輸出流迭代器 cout << endl; //說白了,就是顯示容器內容 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集合,用了一個插入迭代器 cout << "Friends they have:/n"; copy(C.begin(), C.end(), out); cout << endl; return 0;}c++ Primer Plus(習題16.9)//這是作者的一個假設,在我們生活中也有很多這樣的假設//他的思路是在數組中排序元素,然后復制到鏈表中(因為鏈表排序是在很麻煩)//借用中間容器實現排序功能的實現,下面就是測試時間#include<iostream>#include<vector>#include<list>#include<algorithm>#include<iterator>#include<ctime> //提供時間函數const int Num=1000000; //這個要足夠大void outint(int n) { std::cout << n << " "; }int main(){ using namespace std; vector<int>vi0(Num); //指定個數的初始化 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; //調用vector的賦值運算符 list<int>li(Num); //指定個數的初始化 copy(vi0.begin(), vi0.end(), li.begin()); //不同容器之間的數據復制 //計算三種方法的時間,方法一,使用使用STL算法對vi進行排序 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"; //第二次測試 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"; //第三次測試 copy(vi0.begin(), vi0.end(), li.begin()); //重置li鏈表 clock_t start_3 = clock(); copy(li.begin(), li.end(), vi.begin()); //把list的值復制到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(習題16.10)//又是修改程序的題目,這最后的習題涉及到智能指針//然后我們要做的就是滿足客戶的額要求,升級我們的程序//不知道加了哪個頭文件導致cout不明確//這題的思路是書上的方案,如果自己做的話可以想排序字符串那樣//只使用指針數組排序,對指針進行排序#include<iostream>#include<string>#include<vector>#include<algorithm> //提供一些STL方法#include<memory> //智能指針頭文件struct Review //結構是一種默認為公有的類{ std::string title; int rating; double price; //增加的成員,書價格};using namespace std; //書上也是按引用傳遞指針的意義非凡,其實不還是指針,沒設呢么區別bool Operator<(shared_ptr<Review>r1, shared_ptr<Review>r2);//按字母排序的bool woreThan(shared_ptr<Review>r1, shared_ptr<Review>r2); //評分排序的bool expensivethen(shared_ptr<Review>r1, shared_ptr<Review>r2); //價格排序的bool FillReview(Review*rr);void ShowReview(shared_ptr<Review>rr); //有點特別,書上的用法void Showmenu();int main(){ Review temp; vector<shared_ptr<Review>>pr; while (FillReview(&temp)) pr.push_back(shared_ptr<Review>(new Review(temp))); //沒認真看書,這個初始化想了好久好久 vector<shared_ptr<Review>>tem(pr); //用vector自帶的初始化,是一個按名稱排序的vector sort(tem.begin(), tem.end()); //創建按指針排序的<運算符,全排序 //按評分排序的 vector<shared_ptr<Review>>tem2(pr); sort(tem2.begin(), tem2.end(), woreThan); //調用函數進行排序,完整弱排序 //按價格排序 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) { //天真的我竟然在后面加&這個 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; //這里不想太麻煩,就選擇評分為優先排序項目 else return false;}bool woreThan(shared_ptr<Review>r1, shared_ptr<Review>r2) //按評分升序{ if (r1->rating<r2->rating) return true; else return false;}bool expensivethen(shared_ptr<Review>r1, shared_ptr<Review>r2) //按價格升序{ 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; //檢查錯誤輸入 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";}
新聞熱點
疑難解答
圖片精選