C++ Primer Plus第六版第十六章string类和标准模板库编程练习答案

1.

using namespace std;
bool IsPalindrome(const string &);
int main()
{
	string input;
	cout << "Enter a string(quit to quit): ";
	while (cin >> input && input != "quit")
	{
		if (IsPalindrome(input))
			cout << "是回文\n";
		else
			cout << "不是回文\n";
		cout << "Enter next string(quit to quit): ";
	}
	return 0;
}
bool IsPalindrome(const string & s)
{
	string temp(s.rbegin(), s.rend());
	return temp == s;
}

2.

using namespace std;
bool IsPalindrome(string &);
int main()
{
	string input;
	cout << "Enter a string(quit to quit): ";
	while (getline(cin, input) && input != "quit")
	{
		if (IsPalindrome(input))
			cout << "是回文\n";
		else
			cout << "不是回文\n";
		cout << "Enter next string(quit to quit): ";
	}
	return 0;
}
bool IsPalindrome(string & s)
{
	string temp;
	for (auto &a : s)
	{
		if (isalpha(a))
		{
			a = tolower(a);
			temp = temp + a;
		}

	}
	string temp1(temp.rbegin(), temp.rend());
	cout << temp;
	return temp1 == temp;
}

3.

#include 
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
	vector<string>wordlist;
	fstream inFile;
	inFile.open("helloword.txt");
	if (!inFile.is_open())
	{
		cout << "没有打开文件: ";
		exit(EXIT_FAILURE);
	}
	string temp;
	inFile >> temp;
	while (inFile.good())
	{
		wordlist.push_back(temp);
		inFile >> temp;
	}
	std::srand(std::time(0));
	int num = wordlist.size();
	char play;
	cout << "Will you play a word game? ";
	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\n"
			<< "one letter ar 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;
			}
			unsigned 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 choice: " << 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 another?  ";
		cin >> play;
		play = tolower(play);
	}
	cout << "Bye\n";
	return 0;
}

4.
注意:unique的工作原理是把不重复的元素移到前面来,并没有真正的去除重复的元素。

#include 
#include
using namespace std;
int reduce(long ar[], int n);
int main()
{
	long a[8] = { 5, 3, 3, 1, 5, 2, 6, 7 };
	int i = reduce(a, 8);
	cout << "返回后的元素是" << i << "个\n";
		return 0;

}
int reduce(long ar[], int n)
{
	sort(ar, ar + n);
	long * a;
	a = unique(ar, ar + n);
	return a - ar;
}

5.

#include 
#include

using namespace std;
template<typename T>
int reduce(T ar[], int n);
int main()
{
	long a[8] = { 1, 3, 3, 4, 5, 6, 6, 7 };
	int i = reduce(a, 8);
	cout << "返回后的元素是" << i << "个\n";
	string b[] = { "asd", "qwe", "zxc","hhh", "qwe" };
	i = reduce(b, 5);
	cout << "返回后的元素是" << i << "个\n";
	return 0;

}
template<typename T>
int reduce(T ar[], int n)
{
	sort(ar, ar + n);
	T * a;
	a = unique(ar, ar + n);
	return a - ar;
}

6.

#include 
#include 
#include 
#include 
using namespace std;
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; }
};
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main()
{
	srand(time(0));
	cout << "Case Study: Bank of Heather Automatic Teller\n";
	cout << "Enter maximun size of queue: ";
	unsigned int qs;
	cin >> qs;
	queue<Customer>line;
	cout << "Enter the average 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;
	Customer 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();
			wait_time = temp.ptime();
			line_wait += cycle - temp.when();
			served++;
			line.pop();
		}
		if (wait_time > 0)
			wait_time--;
		sum_line += line.size();
	}
	if (customers > 0)
	{
		cout << "customers accepted: " << customers << endl;
		cout << "  customers served: " << served << endl;
		cout << "        turnaway:   " << 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);
}
void Customer::Set(long when)
{
	processtime = rand() % 3 + 1;
	arrive = when;
}

7.

#include 
#include 
#include 
#include 
#include 
using namespace std;
vector<int>lotto(int n, int m);
int main()
{
	vector<int> winners;
	winners = lotto(51, 6);
	for (auto b : winners)
		cout << b << " ";

	return 0;
}
vector<int>lotto(int n, int m)
{
	vector<int>temp(n);
	for (int i = 0; i < n; i++)
		temp[i] = i + 1;
	random_shuffle(temp.begin(), temp.end());
	vector<int>choice(m);
	for (int i = 0; i < m; i++)
		choice[i] = temp[i];
	return choice;
}

8.

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int main()
{
	set<string> mat;
	set<string> pat;
	set<string> Union;
	ostream_iterator<string, char> out(cout, " ");
	cout << "Enter mat's friends: (empty line to quit): ";
	string temp;
	while (getline(cin, temp) && temp != "\0")
	{
		mat.insert(temp);
		cout << "Enter mat's friends: (empty line to quit): ";
	}
	cout << endl;
	cout << "These are mat's friend: " << endl;
	copy(mat.begin(), mat.end(), out);
	cout << endl;
	cout << "Enter pat's friends: (empty line to quit): ";

	while (getline(cin, temp) && temp != "\0")
	{
		pat.insert(temp);
		cout << "Enter mat's friends: (empty line to quit): ";
	}
	cout << "These are pat's friend: " << endl;
	copy(pat.begin(), pat.end(), out);
	cout << endl;
	set_union(mat.begin(), mat.end(),
		pat.begin(), pat.end(), insert_iterator<set<string>>(Union, Union.begin()));
	cout << "these are union: " << endl;
	copy(Union.begin(), Union.end(), out);

	return 0;
}

9.

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int main()
{
	vector<int>v;
	srand(time(0));
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(rand());
	}
	vector<int>vi = v;
	list<int>li(v.begin(), v.end());

	clock_t start = clock();
	sort(vi.begin(), vi.end());
	clock_t End = clock();
	cout << "time is: " << (double)(End - start) / CLOCKS_PER_SEC << "s.\n";

	start = clock();
	li.sort();
	End = clock();
	cout << "time is: " << (double)(End - start) / CLOCKS_PER_SEC << "s.\n";

	copy(v.begin(), v.end(), li.begin());
	start = clock();
	copy(li.begin(), li.end(), vi.begin());
	sort(vi.begin(), vi.end());
	copy(vi.begin(), vi.end(), li.begin());
	End = clock();
	cout << "time is: " << (double)(End - start) / CLOCKS_PER_SEC << "s.\n";
}

10.

#include 
#include
#include
#include
#include
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 betterthan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool expensivethan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool cheapthan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool FillReview(Review & rr);
void ShowReview(const shared_ptr<Review> & rr);
void show();
int main()
{
	using namespace std;
	vector<shared_ptr<Review>> books;
	Review temp;
	while (FillReview(temp))
	{
		shared_ptr<Review> newtemp(new Review(temp));
		books.push_back(newtemp);
	}
	if (books.size() > 0)
	{
		cout << "Thank you. you entered :"
			<< books.size() << " ratings:\n";
		int input;
		show();
		cout << "choose a type to show: ";
		while (cin >> input && input != 7)
		{
			switch (input)
			{
			case 1:
				break;
			case 2:
				sort(books.begin(), books.end());
				break;
			case 3:
				sort(books.begin(), books.end(), worseThan);
				break;
			case 4:
				sort(books.begin(), books.end(), betterthan);
				break;
			case 5:
				sort(books.begin(), books.end(), cheapthan);
				break;
			case 6:
				sort(books.begin(), books.end(), expensivethan);
				break;
			}
			cout << "Rating\tBook\tPrice\n";
			for_each(books.begin(), books.end(), ShowReview);
			cout << "choose a type to show: ";
		}
	}
	else
		cout << "No entries.";
	cout << "Bye.\n";
	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 betterthan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
	if (r1->rating > r2->rating)
		return true;
	else
		return false;
}

bool expensivethan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
{
	if (r1->price > r2->price)
		return true;
	else
		return false;
}

bool cheapthan(const shared_ptr<Review> & r1, const 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: ";
	std::cin >> rr.price;
	if (!std::cin)
		return false;
	while (std::cin.get() != '\n')
		continue;
	return true;
}
void ShowReview(const shared_ptr<Review> & rr)
{
	std::cout << rr->rating << "\t" << rr->title << '\t' << rr->price << std::endl;
}
void show()
{
	cout << "1.Display in original order\n";
	cout << "2.Display in alphabetical order\n";
	cout << "3.Display in ascending order by rating\n";
	cout << "4.Display in descending order by rating\n";
	cout << "5.Display in ascending order by price\n";
	cout << "6.Displayed in descending order by price\n";
	cout << "7.quit\n";
}

你可能感兴趣的:(c++,primer,plus,C++,Primer,Plus第六版,第十六章,string类和标准模板库,编程练习,答案)