第十六章 编程练习答案
这章看的不仔细,第4,10题完全是看网上的额。感觉第一次看不太熟悉,完全不知道说什么,做完题有点明白STL是什么了。
1.
#include <iostream>
#include <string>
#include <algorithm>
using std::string;
bool judge(const string & str);
int main()
{
using std::cout;
using std::endl;
using std::cin;
string t1;
cout << "Please enter the string: ";
cin >> t1;
int ans = judge(t1);
if (ans > 0)
cout << "true" << endl;
if (ans == 0)
cout << "false" << endl;
return 0;
}
bool judge(const string & str)
{
string temp;
temp = str;
reverse(temp.begin(), temp.end());//反转函数,直接用
return temp == str;
}
2.
与第一题基本类似,就是加了一个对字符串的处理
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using std::string;
using std::cout;
using std::endl;
using std::cin;
bool judge(const string & str);
char toLower(char ch) {return tolower(ch); }
int main()
{
string t1;
cout << "Please enter the string: ";
getline(cin, t1);
int ans = judge(t1);
if (ans > 0)
cout << "true" << endl;
if (ans == 0)
cout << "false" << endl;
return 0;
}
bool judge(const string & str)
{
//对输入字符串进行处理,去掉其他符号,
//全部变为小写后进行比较
string temp;
for (int i = 0; i < (int)str.size(); ++i)
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
temp.push_back(tolower(str[i]));//push_back作用是字符串之后插入一个字符
}
string s1 = temp;
reverse(temp.begin(), temp.end());
return temp == s1;
}
3.
这题用了书上16-2的读取文件的方法,没有用提示给的思路。
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <fstream>
#include <cstdlib>
using std::string;
const int NUM = 26;
int main()
{
using std::cout;
using std::cin;
using std::tolower;
using std::endl;
std::srand(std::time(0));
//用文件打开字符串
string wl[NUM];
std::ifstream fin;
fin.open("U16p3.txt");
if (fin.is_open() == false)
{
std::cerr << "Can't open file. Bye.\n";
exit(EXIT_FAILURE);
}
string item;
int count = 0;
getline(fin, item, ',');//,是分界字符
while (fin)
{
wl[count] = item;
getline(fin, item, ',');
++count;
}
fin.close();
const string wordlist[NUM] = wl;
//后面不用修改
char play;
cout << "Will you play a word game? <y/n>";
cin >> play;
play = tolower(play);
while (play == 'y')
{
string target = wordlist[std::rand() % NUM];
int length = target.length();
string attempt(length, '-');
string badchars;
int guesses = 6;
cout << "Guess my secret word. It has " << length << " letters, and you guess"
"\none letter at a time. You get " << guesses << " wrong guesses.\n";
cout << "Your word: " << attempt << endl;
while (guesses > 0 && attempt != target)
{
char letter;
cout << "Guess a letter: ";
cin >> letter;
if (badchars.find(letter) != string::npos
|| attempt.find(letter) !=string::npos)
{
cout << "You already guess that. Try again.\n";
continue;
}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "Oh, bad guess!\n";
--guesses;
badchars += letter;
}
else
{
cout << "Good guess!\n";
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
}
}
cout << "Your word: " << attempt << endl;
if (attempt != target)
{
if (badchars.length() > 0)
cout << "Bad choices: " << badchars << endl;
cout << guesses << " bad guesses left\n";
}
}
if (guesses > 0)
cout << "That's right!\n";
else
cout << "Sorry, the world is " << target << ".\n";
cout << "Will you play another? <y/n> ";
cin >> play;
play = tolower(play);
}
cout << "Bye\n";
return 0;
}
4.
#include <iostream>
#include <algorithm>
int reduce(long ar[], int n);
using namespace std;
int main()
{
long ar[10] = {11, 3, 5, 9, 7, 4, 3, 5, 11, 3};
cout << "The data: ";
for (int i = 0; i < 10; ++i) {
cout << ar[i] << " ";
}
cout << endl;
cout << "After sort and unique: ";
int n = reduce(ar, 10);
for (int i = 0; i < n; ++i) {
cout << ar[i] << " ";
}
cout << endl;
return 0;
}
int reduce(long ar[], int n)
{
//STL的sort()和unique()两个函数
sort(ar, ar + n);
long* p = unique(ar, ar + n);
return (int)(p - ar);
}
5.
#include <iostream>
#include <algorithm>
template <class T>
int reduce(T str[], int n);
using namespace std;
int main()
{
long ar[10] = {11, 3, 5, 9, 7, 4, 3, 5, 11, 3};
cout << "The data: ";
for (int i = 0; i < 10; ++i) {
cout << ar[i] << " ";
}
cout << endl;
cout << "After sort and unique: ";
int n = reduce(ar, 10);
for (int i = 0; i < n; ++i) {
cout << ar[i] << " ";
}
cout << endl << endl;
string str[10] = {"Bob", "Alex", "Candy", "Tony", "Zippo", "Candy", "Bob", "Jim", "Candy", "Zippo"};
cout << "The string: ";
for (int i = 0; i < 10; ++i) {
cout << str[i] << " ";
}
cout << endl;
cout << "After sort and unique: ";
int m = reduce(str, 10);
for (int i = 0; i < m; ++i) {
cout << str[i] << " ";
}
cout << endl;
return 0;
}
template <class T>
int reduce(T str[], int n)
{
sort(str, str + n);
T* p = unique(str, str + n);
return (int)(p - str);
}
6.
#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 std::cin;
using std::cout;
using std::endl;
using std::ios_base;
std::srand(std::time(0));//随机初始化
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maxmium size of queue: ";//最大的排队人数
int qs;
cin >> qs;
std::queue <Item>line;//设有qs个人的队伍
cout << "Enter the number of simulation hours: ";
int hours;
cin >> hours;
long cyclelimit = MIN_PER_HR * hours;
cout << "Enter the average number of customers per hours: ";
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 (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust))
{
if (line.size()==qs)
turnaways++;
else
{
customers++;
temp.set(cycle);
line.push(temp);
}
}
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();
}
//报告结果
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 (std::rand() * x / RAND_MAX < 1);
}
7.
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;
vector<int> Lotto(int m, int n);
void show(int n) {cout << n << " ";}
int main()
{
srand((int)time(0));//用时间产生随机数种子
cout << "Diaplsy the random number:" << endl;
vector<int> winner;
winner = Lotto(51, 6);
for_each(winner.begin(), winner.end(), show);
return 0;
}
vector<int> Lotto(int m, int n)
{
vector<int> temp;
for (int i = 1; i <= m; i++)//创建矢量
{
temp.push_back(i);//vector<int>输入
}
random_shuffle(temp.begin(), temp.end());//随机排列
vector<int>::iterator last;
last = (temp.begin(), temp.begin() + n);
temp.erase(last, temp.end());//取前六位数字
//另外一种比较方便的方法:temp.resize(n);
return temp;
}
8.
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
void show(string & s);
int main()
{
list<string> Mat;
cout << "-----------Mat's friends-----------" << endl;
cout << "Enter the name, and (quit to quit):" << endl;
string temp1;
getline(cin, temp1);
while (temp1 != "quit")
{
Mat.push_back(temp1);
cout << "Enter the name, and (quit to quit):" << endl;
getline(cin, temp1);
}
Mat.sort();
cout << "Here are Mat's friends:" <<endl;
for_each(Mat.begin(), Mat.end(), show);
cout << endl;
list<string> Pat;
cout << "-----------Pat's friends-----------" << endl;
cout << "Enter the name, and (quit to quit):" << endl;
string temp2;
getline(cin, temp2);
while (temp2 != "quit")
{
Pat.push_back(temp2);
cout << "Enter the name, and (quit to quit):" << endl;
getline(cin, temp2);
}
Pat.sort();
cout << "Here are Pat's friends:" <<endl;
for_each(Pat.begin(), Pat.end(), show);
cout << endl;
cout << "--------------friends--------------" << endl;
Mat.splice(Mat.end(), Pat);
Mat.sort();
Mat.unique();
cout << "All friends:" <<endl;
for_each(Mat.begin(), Mat.end(), show);
return 0;
}
void show(string & s)
{
cout << "friend'name:"<< s << endl;
}
9.
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <ctime>
using namespace std;
const int num = 1000000;
int main()
{
vector<int> vi0;
vector<int> vi;
list<int> li;
srand((int)time(0));//用时间产生随机数种子
for (int i = 0; i < num; i++)//初始化
{
int temp = rand() * rand();
vi0.push_back(temp);
vi.push_back(temp);
li.push_back(temp);
}
cout << "The time of sort() by STL: " << endl;
clock_t start1 = clock();
sort(vi.begin(), vi.end());
clock_t end1 = clock();
cout << (double)(end1 - start1) /CLOCKS_PER_SEC;
cout << endl;
cout << "The time of sort() by list: " << endl;
clock_t start2 = clock();
li.sort();
clock_t end2 = clock();
cout << (double)(end2 - start2) /CLOCKS_PER_SEC;
cout << endl;
cout << "The time of sort() by copy: " << endl;
copy(vi0.begin(), vi0.end(), li.begin());
clock_t start3 = clock();
copy(li.begin(), li.end(), vi.begin());
sort(vi.begin(), vi.end());
copy(vi.begin(), vi.end(), li.begin());
clock_t end3 = clock();
cout << (double)(end3 - start3) /CLOCKS_PER_SEC;
cout << endl;
return 0;
}
10.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include<memory>
using namespace std;
struct Review {
std::string title;
int rating;
double price;
};
bool operator<(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool FillReview(Review & rr);
void ShowReview(const shared_ptr<Review> & rr);
void showmenu();
bool sorting1(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
int main()
{
vector <shared_ptr<Review>> books;
Review temp;
while (FillReview(temp)) {
shared_ptr<Review> pd_temp(new Review(temp));
books.push_back(pd_temp);
}
if (books.size() > 0)
{
cout<< "choose a way to show data.";
int choice;
showmenu();
cin >> choice;
while (choice <= 7 && choice > 0)
{
switch (choice)
{
case 1:
for_each(books.begin(), books.end(), ShowReview);
break;
case 2:
sort(books.begin(), books.end());
for_each(books.begin(), books.end(), ShowReview);
break;
case 3:
sort(books.begin(), books.end(), worseThan);
for_each(books.begin(), books.end(), ShowReview);
break;
case 4:
sort(books.begin(), books.end(), worseThan);
reverse(books.begin(), books.end());
for_each(books.begin(), books.end(), ShowReview);
break;
case 5:
sort(books.begin(), books.end(), sorting1);
for_each(books.begin(), books.end(), ShowReview);
break;
case 6:
sort(books.begin(), books.end(), sorting1);
reverse(books.begin(), books.end());
for_each(books.begin(), books.end(), ShowReview);
break;
default:
cout << "wrong number.";
continue;
}
showmenu();
cin >> choice;
}
}
else
cout << "No entries. ";
cout << "Bye.\n";
// cin.get();
return 0;
}
bool operator<(const shared_ptr<Review> & r1, const 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 worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
if (r1->rating < r2->rating)
return true;
else
return false;
}
bool FillReview(Review & rr)
{
std::cout << "Enter book title (quit to quit): ";
getline(cin, rr.title);
if (rr.title == "quit")
return false;
cout << "Enter book price: ";
cin >> rr.price;
if (!cin)
return false;
std::cout << "Enter book rating: ";
std::cin >> rr.rating;
if (!cin)
return false;
// get rid of rest of input line
while (std::cin.get() != '\n')
continue;
return true;
}
void ShowReview(const shared_ptr<Review> & rr)
{
cout << "name\trating\tprice\n";
cout << rr->title << "\t" << rr->rating << "\t" << rr->price << endl;
}
bool sorting1(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
if (r1->price < r2->price)
return true;
if (r1->price == r2->price && r1->rating < r2->rating)
return true;
else
return false;
}
void showmenu()
{
cout << "Please enter 1,2,3,4,5,6 or 7\n"
<< "1) by original order \t 2) by alphabet order \n"
<< "3) by rating up \t 4) by rating down \n"
<< "5) by pricing up \t 6) by pricing down \n"
<< "7) quit \n";
}