《C++ Primer Plus》(第6版)第16章编程练习
《C++ Primer Plus》(第6版)第16章编程练习
1. 回文串
回文指的是顺读和逆读都一样的字符串。例如,“tot”和“otto”都是简短的回文。编写一个程序,让用户输入字符串,并将字符串引用传递给一个bool函数。如果字符串时回文,该函数将返回true,否则返回false。此时,不要担心诸如大小写、空格和标点符号这些复杂的问题。即这个简单的版本将拒绝"Otto”和“Madam, I’m Adam”。请查看附录F中的字符串方法列表,以简化这项任务。
程序:
#include <iostream>
#include <string>
using std::string;
bool isPalindrome(const string &);
int main()
{
using std::cin;
using std::cout;
using std::endl;
string s;
cout << "Please enter a string, I'll tell you if it's a palindrome string" << endl;
cin >> s;
if (isPalindrome(s))
cout << "Yes! \"" << s << "\" is a palindrome string" << endl;
else
cout << "No, \"" << s << "\" isn't a palindrome string" << endl;
system("pause");
return 0;
}
bool isPalindrome(const string &s)
{
int len = s.size();
for (int i = 0; i < len / 2; i++)
{
if (s[i] != s[len - i - 1])
return false;
}
return true;
}
运行结果:


优化:
bool isPalindrome(const string &s)
{
string rev(s.rbegin(), s.rend());
return rev == s;
}
2. 复杂的回文串
与编程练习1中给出的问题相同,但要考虑诸如大小写、空格和标点符号这样的复杂问题。即“Madam, I’m Adam”将作为回文来测试。例如,测试函数可能会将字符串缩略为“madamimadam”,然后测试倒过来是否一样。不要忘了有用的cctype库,您可能从中找到几个有用的STL函数,尽管不一定非要使用它们。
程序:
#include <iostream>
#include <string>
using std::string;
bool isPalindrome(const string &);
int main()
{
using std::cin;
using std::cout;
using std::endl;
string s;
cout << "Please enter a string, I'll tell you if it's a palindrome string" << endl;
getline(cin, s);
string temp = "";
for (int i = 0; i < s.size(); i++)
{
if (isalpha(s[i]))
temp += tolower(s[i]);
}
// cout << temp << endl;
if (isPalindrome(temp))
cout << "Yes! \"" << s << "\" is a palindrome string" << endl;
else
cout << "No, \"" << s << "\" isn't a palindrome string" << endl;
system("pause");
return 0;
}
bool isPalindrome(const string &s)
{
string rev(s.rbegin(), s.rend());
return rev == s;
}
运行结果:

3. 使用vector类修改程序清单16.3
修改程序清单16.3,使之从文件中读取单词。一种方案是,使用vector对象而不是string数组。这样便可以使用push_back()将数据文件中的单词复制到vector对象中,并使用size()来确定单词列表的长度。由于程序应该每次从文件中读取一个单词,因此应使用运算符>>而不是getline()。文件中包含的单词应该用空格、制表符或换行符分隔。
程序:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <vector>
#include <fstream>
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::tolower;
using std::vector;
std::srand(time(0));
vector<string> wordList;
std::ifstream fin;
fin.open("wordList.txt");
if (!fin.is_open())
{
cout << "Can't open file wordList.txt\n";
exit(EXIT_FAILURE);
}
string temp;
while (fin >> temp)
{
wordList.push_back(temp);
}
char play;
cout << "Will you play a word game? <y/n>";
cin >> play;
play = tolower(play);
while (play == 'y')
{
string target = wordList[std::rand() % wordList.size()];
int length = target.length();
string attempt(length, '-');
string badchars;
int guesses = 6;
cout << "Guess my secret word. It has " << length
<< " letters, and you guess\n"
<< "one 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 guessed 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;
// check if letter appears again
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 word is " << target << ".\n";
cout << "Will you play a word game? <y/n>";
cin >> play;
play = tolower(play);
}
cout << "Bye.\n";
system("pause");
return 0;
}
wordList.txt:

运行结果:

4. reduce函数
编写一个具有老式风格接口的函数,其原型如下:
int reduce(long ar[], int n);
实参应是数组名和数组中的元素个数。该函数对数组进行排序,删除重复的值,返回缩减后数组中的元素数目。请使用STL函数编写该函数(如果决定使用通用的unique()函数,请注意它将返回结果区间的结尾)。使用一个小程序测试该函数。
程序:
#include <iostream>
#include <list>
const int ArrSize = 10;
int reduce(long ar[], int n);
int main()
{
using std::cout;
using std::endl;
long arr[ArrSize] = {11, 11, 22, 22, 33, 44, 55, 55, 44, 33};
cout << "Original array:" << endl;
for (int i = 0; i < ArrSize; i++)
{
cout << arr[i] << " ";
}
cout << endl;
int len = reduce(arr, ArrSize);
cout << "After sorting and removing duplicate values,"
<< " array retains " << len << " elements" << endl;
cout << "Current array:" << endl;
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
int reduce(long ar[], int n)
{
using std::list;
list<long> lar;
int count = 0;
for (int i = 0; i < n; i++)
lar.push_back(ar[i]);
lar.sort();
lar.unique();
for (list<long>::iterator it = lar.begin(); it != lar.end(); it++)
{
ar[count++] = (*it);
}
return count;
}
运行结果:

5. 模板函数reduce(T ar[], int n)
问题与编程练习4相同,但要编写一个模板函数:
template<class T>
int reduce(T ar[], int n);
在一个使用long实例和string实例的小程序中测试该函数。
程序:
#include <iostream>
#include <string>
#include <list>
const int ArrSize = 10;
template <class T>
int reduce(T ar[], int n);
int main()
{
using std::cout;
using std::endl;
using std::string;
long arr[ArrSize] = {11, 11, 22, 22, 33, 44, 55, 55, 44, 33};
string str[ArrSize] = {"beetle", "loaner", "stolid", "stupid", "remote",
"loaner", "beetle", "apiary", "whence", "insult"};
cout << "Original long array:" << endl;
for (int i = 0; i < ArrSize; i++)
{
cout << arr[i] << " ";
}
cout << endl;
int len = reduce(arr, ArrSize);
cout << "After sorting and removing duplicate values,"
<< " array retains " << len << " elements" << endl;
cout << "Current long array:" << endl;
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
cout << endl;
cout << "Original string array:" << endl;
for (int i = 0; i < ArrSize; i++)
{
cout << str[i] << " ";
}
cout << endl;
len = reduce(str, ArrSize);
cout << "After sorting and removing duplicate values,"
<< " array retains " << len << " elements" << endl;
cout << "Current string array:" << endl;
for (int i = 0; i < len; i++)
{
cout << str[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
template <class T>
int reduce(T ar[], int n)
{
std::list<T> lar;
int count = 0;
for (int i = 0; i < n; i++)
lar.push_back(ar[i]);
lar.sort();
lar.unique();
for (typename ::std::list<T>::iterator it = lar.begin(); it != lar.end(); it++)
{
ar[count++] = (*it);
}
return count;
}
运行结果:

注意:list::iterator it是不可以编译通过的。
解决办法:
error: need ‘typename’ before '…'的解决方法
C++:进阶之旅:need ‘typename’ before ‘std::vector::iterator’ because ‘std::vector’ is a dependent scope
6. 使用STL queue模板类重新编写程序清单12.12
使用STL queue模板类而不是第12章的Queue类,重新编写程序清单12.12所示的示例。
程序:
customer.h:
#ifndef CUSTOMER_H
#define CUSTOMER_H
class Customer
{
private:
long arrive;
int processtime;
public:
Customer() { arrive = processtime = 0; }
void set(long when);
long when() const { return arrive; }
int ptime() const { return processtime; }
};
typedef Customer Item;
#endif
customer.cpp:
#include <cstdlib> //for rand()
#include "customer.h"
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
bank.cpp:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>
#include "customer.h"
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 maximum size of queue: ";
int qs;
cin >> qs;
std::queue<Item> line;
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 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 (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())
{
temp = line.front();
line.pop();
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.precision(2);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << "average queue size: "
<< (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);
}
运行结果:
C:\Users\81228\Documents\Program\VScode C++ Program\chapter16\16.6>g++ customer.cpp bank.cpp -o bank
C:\Users\81228\Documents\Program\VScode C++ Program\chapter16\16.6>bank
Case Study: Bank of Heather Automatic Teller
Enter maximum size of queue: 10
Enter the number of simulation hours: 100
Enter the average number of customers per hour: 15
customers accepted: 1471
customers served: 1471
turnaways: 0
average queue size: 0.15
average wait time: 0.59 minutes
Done!
C:\Users\81228\Documents\Program\VScode C++ Program\chapter16\16.6>
7. 彩票卡游戏
彩票卡是一个常见的游戏。卡片上带编号的圆点,其中一些圆点被随机选中。编写一个lotto()函数,它接受两个参数。第一个参数是彩票卡上圆点的个数,第二个参数是随机选择的圆点个数。该函数返回一个vector对象,其中包含(按排列后的顺序)随机选择的号码。例如,可以这样使用该函数:
vector<int> winners;
winners = Lotto(51,6);
这样将把一个矢量赋给winner,该矢量包含1~51中随机选定的6个数字。注意,仅仅使用rand()无法完成这项任务,因它会生成重复的值。提示:让函数创建一个包含所有可能值的矢量,使用random_shuffle(),然后通过打乱后的矢量的第一个值来获取值。编写一个小程序来测试这个函数。
程序:
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
vector<int> lotto(int, int);
void show(vector<int>);
int main()
{
vector<int> winners;
winners = lotto(51, 6);
show(winners);
system("pause");
return 0;
}
vector<int> lotto(int m, int n)
{
vector<int> temp;
vector<int> result;
for (int i = 0; i < m; i++)
temp.push_back(i + 1);
for (int i = 0; i < n; i++)
{
random_shuffle(temp.begin(), temp.end());
result.push_back(temp[0]);
}
return result;
}
void show(vector<int> v)
{
using std::cout;
using std::endl;
int len = v.size();
for (int i = 0; i < len; i++)
cout << v[i] << " ";
cout << endl;
}
运行结果:

8. Mat和Pat的派对
Mat和Pat希望邀请他们的朋友来参加派对。他们要编写一个程序完成下面的任务。
- 让Mat输入他朋友的姓名列表。姓名存储在一个容器中,然后按排列后的顺序显示出来。
- 让Pat输入她朋友的姓名列表。姓名存储在另一个容器中,然后按排列后的顺序显示出来。
- 创建第三个容器,将两个列表合并,删除重复的部分,并显示这个容器的内容。
程序:
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using std::list;
using std::string;
void show(list<string>);
int main()
{
using std::cin;
using std::cout;
list<string> mat, pat, final;
string name;
cout << "Please enter Mat's friends' name (q to quit):\n";
while (getline(cin, name))
{
if (name == "q")
break;
mat.push_back(name);
cout << "Enter Mat's friends' name (q for quit):\n";
}
cout << "Please enter Pat's friends' name (q for quit):\n";
while (getline(cin, name))
{
if (name == "q")
break;
pat.push_back(name);
cout << "Enter Pat's friends' name (q for quit):\n";
}
mat.sort();
cout << "Mat's friend:\n";
show(mat);
pat.sort();
cout << "Pat's friend:\n";
show(pat);
final.merge(mat);
final.merge(pat);
final.sort();
final.unique();
cout << "Merge mat and pat's friends and delete the duplicate parts:\n";
show(final);
system("pause");
return 0;
}
void show(list<string> ls)
{
using std::cout;
using std::endl;
for (list<string>::iterator it = ls.begin(); it != ls.end(); it++)
cout << (*it) << " ";
cout << endl;
}
运行结果:

9. 数组和链表
相对于数组,在链表中添加和删除元素更容易,但排序速度更慢。这就引出了一种可能性:相对于使用链表算法进行排序,将链表复制到数组中,对数组进行排序,再将排序后的结果复制到链表中的速度可能更快;但这也可能占用更多的内存。请使用如下方法检验上述假设。
a. 创建大型vector对象vi0,并使用rand()给它提供初始值。
b. 创建vector对象vi和list对象li,它们的长度都和初始值与vi0相同。
c. 计算使用STL算法sort()对vi进行排序所需的时间,再计算使用list的方法sort()对li进行排序所需的时间。
d. 将li重置为排序的vi0的内容,并计算执行如下操作所需的时间:将li的内容复制到vi中,对vi进行排序,并将结果复制到li中。
要计算这些操作所需的时间,可使用ctime库中的clock()。正如程序清单5.14演示的,可使用下面的语句来获取开始时间:
clock_t start = clock();
再在操作结束后使用下面的语句获取经过了多长时间:
clock_t end = clock();
cout << (double)(end - start)/CLOCKS_PER_SEC;
这种测试并非绝对可靠,因为结果取决于很多因素,如可用内存量、是否支持多处理以及数组(列表)的长度(随着要排序的元素数增加,数组相对于列表的效率将更明显)。另外,如果编译器提供了默认生成方式和发布生成方式,请使用发布生成方式。鉴于当今计算机的速度非常快,要获得有意义的结果,可能需要使用尽可能大的数组。例如,可尝试包含100000、1000000和10000000个元素。
程序:
在这里插入代码片
运行结果:
当数组包含100000个元素时:

当数组包含1000000个元素时:

当数组包含10000000个元素时:

10. 修改程序清单16.9
请按如下方式修改程序清单16.9(vect3.cpp)。
a. 在结构Review中添加成员price。
b. 不使用vector来存储输入,而使用vector<shared_ptr>。别忘了,必须使用new返回的指针来初始化shared_ptr。
c. 在输入阶段结束后,使用一个循环让用户选择如下方式之一显示书籍:按原始顺序显示、按字母表顺序显示、按评级升序显示、按评级降序显示、按价格升序显示、按价格降序显示、退出。
下面是一种可能的解决方案:获取输入后,再创建一个shared_ptr矢量,并用原始数组初始化它。定义一个对指向结构的指针进行比较的operator<()函数,并使用它对第二个矢量进行排序,让其中的shared_ptr按其指向的对象中的书名排序。重复上述过程,创建按rating和price排序的shared_ptr矢量。请注意,通过使用rbegin()和rend(),可避免创建按相反的顺序排列的shared_ptr矢量。
程序:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>
using std::shared_ptr;
using std::string;
struct Review
{
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 cheaperThan(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2);
bool FillReview(shared_ptr<Review> &rr);
void ShowReview(shared_ptr<Review> &rr);
void ShowChoice();
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::vector;
vector<shared_ptr<Review>> books;
shared_ptr<Review> temp(new Review);
int n;
while (FillReview(temp))
{
books.push_back(temp);
temp = shared_ptr<Review>(new Review);
}
ShowChoice();
cin >> n;
while (n < 7 && n > 0)
{
switch (n)
{
case 1:
// 原始顺序
cout << "title\trating\tprice\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 2:
// 字母表顺序
sort(books.begin(), books.end());
cout << "title\trating\tprice\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 3:
// 评级升序
sort(books.begin(), books.end(), worseThan);
cout << "title\trating\tprice\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 4:
// 评级降序
sort(books.begin(), books.end(), worseThan);
reverse(books.begin(), books.end());
cout << "title\trating\tprice\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 5:
// 价格升序
sort(books.begin(), books.end(), cheaperThan);
cout << "title\trating\tprice\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 6:
// 价格降序
sort(books.begin(), books.end(), cheaperThan);
reverse(books.begin(), books.end());
cout << "title\trating\tprice\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 7:
break;
default:
cout << "wrong number.";
continue;
}
ShowChoice();
cin >> n;
}
cout << "Bye.\n";
system("pause");
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 if (r1->title == r2->title && r1->rating == r2->rating && r1->price < r2->price)
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 cheaperThan(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2)
{
if (r1->price < r2->price)
return true;
else
return false;
}
bool FillReview(shared_ptr<Review> &rr)
{
using std::cin;
using std::cout;
cout << "Enter book title (quit to quit): ";
std::getline(cin, rr->title);
if (rr->title == "quit")
{
return false;
}
cout << "Enter book rating: ";
cin >> rr->rating;
if (!cin)
return false;
while (cin.get() != '\n')
continue;
cout << "Enter book price: ";
cin >> rr->price;
if (!cin)
return false;
while (cin.get() != '\n')
continue;
return true;
}
void ShowReview(shared_ptr<Review> &rr)
{
using std::cout;
using std::endl;
cout << rr->title << "\t" << rr->rating << "\t" << rr->price << endl;
}
void ShowChoice()
{
using std::cout;
cout << "Please enter 1~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";
}
运行结果:
Enter book title (quit to quit): Flying fish
Enter book rating: 8
Enter book price: 13.99
Enter book title (quit to quit): Bocchi the Rock
Enter book rating: 10
Enter book price: 100
Enter book title (quit to quit): The Wind Says
Enter book rating: 4
Enter book price: 9.99
Enter book title (quit to quit): Farewell and Delete
Enter book rating: 7
Enter book price: 50
Enter book title (quit to quit): quit
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
1
title rating price
Flying fish 8 13.99
Bocchi the Rock 10 100
The Wind Says 4 9.99
Farewell and Delete 7 50
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
2
title rating price
Bocchi the Rock 10 100
Farewell and Delete 7 50
Flying fish 8 13.99
The Wind Says 4 9.99
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
3
title rating price
The Wind Says 4 9.99
Farewell and Delete 7 50
Flying fish 8 13.99
Bocchi the Rock 10 100
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
4
title rating price
Bocchi the Rock 10 100
Flying fish 8 13.99
Farewell and Delete 7 50
The Wind Says 4 9.99
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
5
title rating price
The Wind Says 4 9.99
Flying fish 8 13.99
Farewell and Delete 7 50
Bocchi the Rock 10 100
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
6
title rating price
Bocchi the Rock 10 100
Farewell and Delete 7 50
Flying fish 8 13.99
The Wind Says 4 9.99
Please enter 1~7
1) by original order 2) by alphabet order
3) by rating up 4) by rating down
5) by pricing up 6) by pricing down
7) quit
本文介绍了《C++PrimerPlus》第六版第16章的多个编程练习,包括实现回文字符串检查、处理复杂回文、使用vector修改程序、实现reduce函数、模板函数以及使用STLqueue和链表。每个练习都展示了如何利用C++标准库和数据结构解决问题。
2507

被折叠的 条评论
为什么被折叠?



