C++ Primer Plus第六版 第十六章 编程练习答案

迭代器有点晕...


//第一题
//main.cpp
#include 
#include 

bool palindrome(const std::string &str);

int main()
{
	std::string str;
	std::cin >> str;
	std::cout << (palindrome(str) ? "是" : "否") << std::endl;

	return 0;
}

bool palindrome(const std::string &str)
{
	for (int begin = 0, end = str.size() - 1; begin < end; ++begin, --end)
	{
		if (str[begin] != str[end])
			return false;
	}
	return true;
}



//第二题
//main.cpp
#include 
#include 
#include 

void simplify(std::string &str);

bool palindrome(const std::string &str);

int main()
{
	std::string str;
	std::getline(std::cin, str);

	simplify(str);

	std::cout << (palindrome(str) ? "是" : "否") << std::endl;

	return 0;
}

void simplify(std::string &str)
{
	std::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]));
	}
	str = temp;
}

bool palindrome(const std::string &str)
{
	for (int begin = 0, end = str.size() - 1; begin < end; ++begin, --end)
	{
		if (str[begin] != str[end])
			return false;
	}
	return true;
}




//第三题
//main.cpp
#include 
#include 
#include 
#include 
#include 
#include 
#include 

const int NUM = 26;
const std::string wordlist[NUM] = {
	"apiary", "beetle", "cereal", "danger",
	"ensign", "florid", "garage", "health",
	"insult", "jackal", "keeper", "loaner",
	"manage", "nonce", "onset", "plaid",
	"quilt", "remote", "stolid", "train",
	"useful", "valid", "whence", "xenon",
	"yearn", "zippy"
};

int main()
{
	std::srand(std::time(0));

	std::vector input;
	
	std::ifstream fin;
	fin.open("data.txt");
	std::string temp;
	while (fin >> temp)
		input.push_back(temp);

	while (!input.empty())
	{
		std::string target = wordlist[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;
		int count = -1;
		while (guesses > 0 && attempt != target && count < (int)input[0].size())
		{
			++count;
			std::cout << "Guess a letter: ";
			if ((badchars.find(input[0][count]) != std::string::npos) || (attempt.find(input[0][count]) != std::string::npos))
			{
				std::cout << "You already guessed that. Try again.\n";
				continue;
			}
			int loc = target.find(input[0][count]);
			if(loc == std::string::npos)
			{
				std::cout << "Oh, bad guess!\n";
				--guesses;
				badchars += input[0][count];
			}
			else
			{
				std::cout << "Good guess!\n";
				attempt[loc] = input[0][count];
				loc = target.find(input[0][count], loc + 1);
				while (loc != std::string::npos)
				{
					attempt[loc] = input[0][count];
					loc = target.find(input[0][count], 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";
		input.erase(input.begin());
	}
	fin.close();
	return 0;
}



//第四题
//main.cpp
#include 
#include 

int reduce(long ar[], int n);

int main()
{
	long ar[5] = { 1, 1, 3, 2, 2 };
	int count = reduce(ar, 5);
	std::cout << "元素数目: " << count << std::endl;
	for (int i = 0; i < count; ++i)
		std::cout << ar[i] << ' ';
	std::cout << std::endl;
	
	return 0;
}

int reduce(long ar[], int n)
{
	std::list list;
	for (int i = 0; i < n; ++i)
		list.push_back(ar[i]);
	list.sort();
	list.unique();

	int count = 0;
	for (std::list::iterator it = list.begin(); it != list.end(); ++it)
		ar[count++] = (*it);
	return count;
}


//第五题
//main.cpp
#include 
#include 

template 
int reduce(T ar[], int n);

int main()
{
	long ar[5] = { 1, 1, 3, 2, 2 };
	int count = reduce(ar, 5);
	std::cout << "元素数目: " << count << std::endl;
	for (int i = 0; i < count; ++i)
		std::cout << ar[i] << ' ';
	std::cout << std::endl;

	std::string ars[5] = { "Tree", "Yuuji", "SHANA" , "Tree", "Yuuji" };
	int counts = reduce(ars, 5);
	std::cout << "元素数目: " << counts << std::endl;
	for (int i = 0; i < counts; ++i)
		std::cout << ars[i].c_str() << ' ';
	std::cout << std::endl;

	return 0;
}

template 
int reduce(T ar[], int n)
{
	std::list list;
	for (int i = 0; i < n; ++i)
		list.push_back(ar[i]);
	list.sort();
	list.unique();

	int count = 0;
	for (std::list::iterator it = list.begin(); it != list.end(); ++it)
		ar[count++] = (*it);
	return count;
}


//第六题
//main.cpp
#include 
#include 
#include 
#include 
#include "customer.h"
const int MIN_PER_HR = 60;

bool newcustomer(double x);

int main()
{
	std::srand(std::time(0));
	std::cout << "Case Study: Bank of Heather Automatic Teller\n";
	std::cout << "Enter maximum size of queue: ";
	int qs;
	std::cin >> qs;
	std::queue line;

	std::cout << "Enter the number of simulation hours: ";
	int hours;
	std::cin >> hours;
	long cyclelimit = MIN_PER_HR * hours;

	std::cout << "Enter the average number of customers per hour: ";
	double perhour;
	std::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();
			wait_time = temp.ptime();
			line_wait += cycle - temp.when();
			++served;
		}
		if (wait_time > 0)
			--wait_time;
		sum_line += line.size();
	}

	if (customers > 0)
	{
		std::cout << "customers accepted: " << customers << std::endl;
		std::cout << " customers serverd: " << served << std::endl;
		std::cout << "     turnaways: " << turnaways << std::endl;
		std::cout << "average queue size: ";
		std::cout.precision(2);
		std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
		std::cout << (double)sum_line / cyclelimit << std::endl;
		std::cout << " average wait time: " << (double)line_wait / served << " minutes  \n";
	}
	else
		std::cout << "No customers!\n";
	std::cout << "Done!\n";

	return 0;
}

bool newcustomer(double x)
{
	return (std::rand() * x / RAND_MAX < 1);
}

//customer.h
#ifndef CUSTOMER_H_
#define CUSTOMER_H_

#include 

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;

#endif



//第七题
//main.cpp
#include 
#include 
#include 
#include 
#include 

std::vector lotto(int n, int s);

int main()
{
	std::srand(std::time(0));
	std::vector winners = lotto(51, 6);
	for (int i = 0; i < winners.size(); ++i)
		std::cout << winners[i] << ' ';
	std::cout << std::endl;

	return 0;
}

std::vector lotto(int n, int s)
{
	std::vector ans;
	std::vector temp;
	for (int i = 1; i <= n; ++i)
		temp.push_back(i);
	for (int i = 0; i < s; ++i)
	{
		std::random_shuffle(temp.begin(), temp.end());
		ans.push_back(temp[i]);
		temp.erase(temp.begin());
	}
	return ans;
}



//第八题
//main.cpp
#include 
#include 
#include 

int main()
{
	std::list Mat;
	std::list Pat;
	std::list Merge;

	do {
		std::string temp;
		std::getline(std::cin, temp);
		if (temp == "quit")
			break;
		Mat.push_back(temp);
	} while (true);
	do {
		std::string temp;
		std::getline(std::cin, temp);
		if (temp == "quit")
			break;
		Pat.push_back(temp);
	} while (true);

	Mat.sort();
	for each (std::string var in Mat)
		std::cout << var << ' ';
	std::cout << std::endl;

	Pat.sort();
	for each (std::string var in Pat)
		std::cout << var << ' ';
	std::cout << std::endl;
	
	Merge = Mat;
	Merge.merge(Pat);
	Merge.unique();
	for each (std::string var in Merge)
		std::cout << var << ' ';
	std::cout << std::endl;

	return 0;
}



//第九题
//main.cpp
#include 
#include 
#include 
#include 
#include 
#include 

const int LEN = 100000;

int main()
{
	std::srand(std::time(0));

	std::vector vi0;
	for (int i = 0; i < LEN; ++i)
		vi0.push_back(std::rand() % 1000);

	std::vector vi = vi0;
	std::list li;
	for (int i = 0; i < LEN; ++i)
		li.push_back(vi0[i]);

	clock_t start = clock();
	std::sort(vi.begin(), vi.end());
	clock_t end = clock();
	std::cout << "vi std::sort: " << (double)(end - start) / CLOCKS_PER_SEC << std::endl;

	start = clock();
	li.sort();
	end = clock();
	std::cout << "li list::sort: " << (double)(end - start) / CLOCKS_PER_SEC << std::endl;

	li.clear();
	vi.clear();
	for (int i = 0; i < LEN; ++i)
		li.push_back(vi0[i]);

	start = clock();
	for each (int var in li)
		vi.push_back(var);
	li.clear();
	std::sort(vi.begin(), vi.end());
	for each (int var in vi)
		li.push_back(var);
	end = clock();
	std::cout << "copy sort copy: " << (double)(end - start) / CLOCKS_PER_SEC << std::endl;

	return 0;
}



//第十题
//main.cpp
#include 
#include 
#include 
#include 
#include 

struct Review {
	std::string title;
	double price;
	int rating;
};

bool ComByAlp(const std::shared_ptr &r1, const std::shared_ptr &r2);
bool ComByRatingAsc(const std::shared_ptr &r1, const std::shared_ptr &r2);
bool ComByRatingDes(const std::shared_ptr &r1, const std::shared_ptr &r2);
bool ComByPriceAsc(const std::shared_ptr &r1, const std::shared_ptr &r2);
bool ComByPriceDes(const std::shared_ptr &r1, const std::shared_ptr &r2);

bool FillReview(Review &rr);
void ShowReview(const std::shared_ptr &rr);

int main()
{
	using namespace std;

	vector> books;
	Review temp;
	while (FillReview(temp))
	{
		shared_ptr t(new Review);
		t->title = temp.title;
		t->rating = temp.rating;
		t->price = temp.price;
		books.push_back(t);
	}
	int flag = true;
	do {
		std::cout << "1、按原始顺序显示\n2、按字母表顺序显示\n3、按评级升序显示\n4、按评级降序显示\n5、按价格升序显示\n6、按价格降序显示\n7、退出\n";
		int cho;
		std::cin >> cho;
		switch (cho)
		{
		case 1:
			for_each(books.begin(), books.end(), ShowReview);
			break;
		case 2:
			std::sort(books.begin(), books.end(), ComByAlp);
			for_each(books.begin(), books.end(), ShowReview);
			break;
		case 3:
			std::sort(books.begin(), books.end(), ComByRatingAsc);
			for_each(books.begin(), books.end(), ShowReview);
			break;
		case 4:
			std::sort(books.begin(), books.end(), ComByRatingDes);
			for_each(books.begin(), books.end(), ShowReview);
			break;
		case 5:
			std::sort(books.begin(), books.end(), ComByPriceAsc);
			for_each(books.begin(), books.end(), ShowReview);
			break;
		case 6:
			std::sort(books.begin(), books.end(), ComByPriceDes);
			for_each(books.begin(), books.end(), ShowReview);
			break;
		case 7:
			flag = false;
			break;
		default:
			break;
		}
	} while (flag);

	cout << "Bye.\n";
	return 0;
}

bool ComByAlp(const std::shared_ptr &r1, const std::shared_ptr &r2)
{
	int len1 = r1->title.size();
	int len2 = r2->title.size();

	for (int i = 0; i < ((len1 < len2) ? len1 : len2); ++i)
	{
		if (r1->title[i] < r2->title[i])
			return true;
		else if (r1->title[i] > r2->title[i])
			return false;
	}
	if (len1 < len2)
		return true;
	return false;
}

bool ComByRatingAsc(const std::shared_ptr &r1, const std::shared_ptr &r2)
{
	return r1->rating < r2->rating;
}

bool ComByRatingDes(const std::shared_ptr &r1, const std::shared_ptr &r2)
{
	return r1->rating > r2->rating;
}

bool ComByPriceAsc(const std::shared_ptr &r1, const std::shared_ptr &r2)
{
	return r1->price < r2->price;
}

bool ComByPriceDes(const std::shared_ptr &r1, const std::shared_ptr &r2)
{
	return r1->price > r2->price;
}

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;
	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 std::shared_ptr &rr)
{
	std::cout << rr->rating << "\t" << rr->price << "\t" << rr->title << std::endl;
}


你可能感兴趣的:(C++,Primer,Plus学习笔记)