C++PrimerPlus学习——第十六章编程练习

16-1

#include <iostream>
#include <string>
using namespace std;
bool IsPalindrome(string str)
{
	int len = str.size();
	for (int i = 0; i < len / 2; i++)
	{
		if (str[i] != str[len - i - 1])
			return false;
	}
	return true;
}
int main()
{
	cout << "Please enter a string:(quit to quit)\n";
	string str;
	while (getline(cin, str))
	{
		if (str == "quit")
			break;
		else if (IsPalindrome(str))
			cout << "Input string is a palindrome.\nPlease enter another string:\n";
		else
			cout << "Input string is not a palindrome.\nPlease enter another string:\n";
	}
	
	return 0;
}

16-2

#include <iostream>
#include <string>
using namespace std;
bool IsPalindrome(string str)
{
	int len = str.size();
	for (int i = 0; i < len / 2; i++)
	{
		if (str[i] != str[len - i - 1])
			return false;
	}
	return true;
}
int main()
{
	cout << "Please enter a string:(quit to quit)\n";
	string str;
	while (getline(cin, str))
	{
		if (str == "quit")
			break;
		int len = str.size();
		string temp = "";
		for (int i = 0; i < len; i++)
		{
			if (isalpha(str[i]))
				temp += tolower(str[i]);
		}
		if (IsPalindrome(temp))
			cout << "Input string is a palindrome.\nPlease enter another string:\n";
		else
			cout << "Input string is not a palindrome.\nPlease enter another string:\n";
	}
	
	return 0;
}

16-3

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	ifstream fin;
	fin.open("C:\\test.txt");
	if (fin.is_open() == false) {
		cerr << "Can't open file.\n";
		exit(EXIT_FAILURE);
	}
	vector<string> strings;
	string item;
	int count = 0;
	while (fin) {
		fin >> item;
		strings.push_back(item);
		count++;
	}
	fin.close();
	for (int i = 0; i < strings.size(); i++)
	{
		cout << strings[i] << " ";
		if (i % 10 == 0)
			cout << endl;
	}
	return 0;
}

16-4

#include <iostream>
#include <algorithm>

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

int main()
{
	using std::cout;
	using std::endl;
	long ar[10] = { 2,2,1,1,4,4,3,3,6,6 };
	for (int i = 0;i<10;i++)
		cout << ar[i] << " ";
	cout << endl;
	int N = reduce(ar, 10);
	for (int i = 0; i < N; i++)
		cout << ar[i] << " ";
	cout << endl;
	cout << N << endl;
	return 0;
}

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

16-5

#include <iostream>
#include <algorithm>
template <class T>
int reduce(T ar[], int n)
{
	std::sort(ar, ar + n);
	T* ar_sorted;
	ar_sorted = std::unique(ar, ar + n);
	return int(ar_sorted - ar);
}

int main()
{
	using std::cout;
	using std::endl;
	long ar[10] = { 2,2,1,1,4,4,3,3,6,6 };
	for (int i = 0;i<10;i++)
		cout << ar[i] << " ";
	cout << endl;
	int N = reduce(ar, 10);
	for (int i = 0; i < N; i++)
		cout << ar[i] << " ";
	cout << endl;
	cout << N << endl;
	return 0;
}

16-6
去掉关于Queue的内容,用queue中类似的功能代替,其他不变
queue.h

#ifndef QUEUE_H_
#define QUEUE_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 // !QUEUE_H_

queue.cpp

#include "queue.h"
#include <cstdlib>

void Customer::set(long when)
{
	processtime = std::rand() % 3 + 1;
	arrive = when;
}

main.cpp

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.h"
#include <queue>

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);
}

16-7

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> Lotto(int m, int n);
void show(vector<int> lot);

int main()
{
    vector<int> winner;
    winner = Lotto(51, 6);
    show(winner);
    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);
    random_shuffle(temp.begin(), temp.end());
    for (int i = 0; i < n; i++)
    {
        result.push_back(temp[i]);
    }
    return result;
}

void show(vector<int> lot)
{
    int len = lot.size();
    for (int i = 0; i < len; i++)
        cout << lot[i] << " ";
    cout << endl;
}

16-8

#include <iostream>
#include <string>
#include <list>
#include <algorithm>

using namespace std;

int main()
{
	list<string> mat, pat, final;
	string name;
	cout << "Please enter mat's friend:(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:\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();
	pat.sort();
	final = mat;
	final.merge(pat);
	final.unique();
	final.sort();
	list<string>::iterator itor = final.begin();
	for (int i = 0; i < final.size(); i++)
		cout << *itor++ << endl;
}

16-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();
        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;
}

16-10
要用shared_ptr,直接using namespace std,出现了cout无法识别的报错,确实不宜用

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>

using std::cout;
using std::cin;
using std::endl;
using std::shared_ptr;
using std::vector;
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()
{
	vector<shared_ptr<Review>> books;
	shared_ptr<Review> temp(new Review);
	while (FillReview(temp)) 
	{
		books.push_back(temp);
		temp = shared_ptr<Review>(new Review);
	}
	
	ShowChoice();
	int n;
	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";
	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)
{
	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 prive: ";
	cin >> rr->price;
	if (!cin)
		return false;
	while (cin.get() != '\n')
		continue;
	return true;
}

void ShowReview(shared_ptr<Review>& rr)
{
	cout << rr->title << "\t" << rr->rating <<  "\t" << rr->price << endl;
}

void ShowChoice()
{
	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";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值