月度归档:2016年07月

C++ Class练习

《C++ Primer Plus》
第12章 课后练习2

#ifndef STRING_H_
#define STRING_H_
#include <iostream>
using std::ostream;
using std::istream;

class String
{
private:
        char * str;
        int len;
        static int num_strings;
        static const int CINLIM = 80;
public:
        String(const char * s);
        String();
        String(const String &);
        ~String();
        int length () const { return len; }

        String & operator=(const String &);
        String & operator=(const char *);

        char & operator[](int i);
        const char & operator[](int i) const;
        void Stringlow();
        void Stringup();
        int has(const char c);
        String operator+(const String & st1);

        operator char *() const;
        friend bool operator<(const String & st1, const String & st2);
        friend bool operator>(const String & st1, const String & st2);
        friend bool operator==(const String & st1, const String & st2);
        friend String operator+(const char *, const String & st1);
        friend ostream & operator<<(ostream & os, const String & st);
        friend istream & operator>>(istream & is, String & st);

        static int HowMany();
};
#endif
#include <cstring>
#include <cctype>
#include "String.h"
#include <iostream>
int String::num_strings = 0;

int String::HowMany()
{
	return num_strings;
}

String::String(const char * s)
{
	len = std::strlen(s);
	str = new char[len+1];
	std::strcpy(str,s);
	num_strings++;
}

String::String()
{
	len = 4;
	str = new char[1];
	str[0] = '\0';
	num_strings++;
}

String::String(const String & st)
{
	num_strings++;
	len = st.len;
	str = new char[len+1];
	std::strcpy(str,st.str);
}

String::~String()
{
	--num_strings;
	delete [] str;
}

String & String::operator=(const String & st)
{
	delete [] str;
	
	len = strlen(st.str);
	str = new char[len+1];
	std::strcpy(str,st.str);
	
	return *this;
}

String & String::operator=(const char * s)
{
	delete [] str;
	len = std::strlen(s);
	str = new char[len+1];
	std::strcpy(str, s);
	return *this;
}

char & String::operator[](int i)
{
	return str[i];
}

bool operator<(const String & st1, const String & st2)
{
	return (std::strcmp(st1.str, st2.str) < 0);
}

bool operator>(const String & st1, const String & st2)
{
	return st2 < st1;
}

bool operator==(const String & st1, const String & st2)
{
	return (std::strcmp(st1.str, st2.str) == 0);
}

ostream & operator<<(ostream & os, const String & st)
{
	os << st.str;
	return os;
}

istream & operator>>(istream & is, String & st)
{
	char temp[String::CINLIM];
	is.get(temp,String::CINLIM);
	if(is)
		st = temp;
	while (is && is.get() != '\n')
		continue;
	return is;
}

void String::Stringlow()
{
	for (int i = 0;i < len; i++)
		str[i] = tolower(str[i]);
}

void String::Stringup()
{
	for (int i = 0;i < len; i++)
		str[i] = toupper(str[i]);
}
/* 错误的重载函数,问题是构造temp的时候,已经使用new 分配了固定长度的内存。使用strcat的时候实际上已经内存溢出了.
String String::operator+(const String & st1)
{
	String temp(str);
	strcat(temp.str,st1.str);
	temp.len = strlen(str) + strlen(st1.str) + 1;
	return temp;
}
*/
String String::operator+(const String & st1)
{
	int nlen = strlen(st1.str) + strlen(str) + 1;
	char * nstr = new char[nlen];
	strcpy(nstr,str);
	strcat(nstr,st1.str);
	String temp;
	delete [] temp.str;
	temp.str = nstr;
	return temp;
}

String::operator char *() const
{
	return str;
}

String operator+(const char * st1,const String & st2)
{
	String temp;
	strcat(temp.str,st1);
	strcat(temp.str,st2.str);
	temp.len = strlen(st1) + st2.len;
	return temp;
}

int String::has(const char c)
{
	int count = 0;
	for(int i = 0; i < len; i++)
			if (str[i] == c )
				count++;
	return count;
}
#include <iostream>
using namespace std;
#include "String2.h"
int main()
{
        String s1(" and I am C++ stdudent.");
        String s2 = "Pleas enter your name: ";
        String s3;
        cout << s2;
        cin >> s3;
        s2 = "My name is " + s3;
        cout << s2 << ".\n";
        s2 = s2 + s1;
        s2.Stringup();
        cout << "The string\n" << s2 << "\ncontains " << s2.has('A')
                << " 'A' characters in it.\n";
        s1 = "red";

        String rgb[3] = { String(s1), String("green"), String("blue") };

        cout << "Enter the name of a primary color for mixing light: ";
        String ans;
        bool success = false;
        while (cin >> ans)
        {
                ans.Stringlow();
                for(int i = 0; i < 3; i++)
                {
                        if(ans == rgb[i])
                        {
                                cout << "That's right!\n";
                                success = true;
                                break;
                        }
                }
                if (success)
                        break;
                else
                        cout << "Try again!\n";
        }
        cout << "Bye\n";
        return 0;
}

第12章 课后练习6

#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;

class Queue
{
private:
        struct Node { Item item; struct Node * next ; };
        enum { Q_SIZE = 10 };

        Node * front;
        Node * rear;
        int items;
        const int qsize;
        Queue(const Queue & q) : qsize(0) { }
        Queue & operator=(const Queue & q) { return *this; }
public:
        Queue( int qs = Q_SIZE );
        ~Queue();
        bool isempty() const;
        bool isfull() const;
        int queuecount() const;
        bool enqueue(const Item & item);
        bool dequeue(Item & item);
};
#endif
#include "queue.h"
#include <cstdlib>
#include <stdio.h>

Queue::Queue(int qs) : qsize(qs)
{
	front = rear = NULL;
	items = 0;
}

Queue::~Queue()
{
	Node * temp;
	while(front != NULL)
	{
		temp = front;
		front = front->next;
		delete temp;
	}
}

bool Queue::isempty() const
{
	return items == 0;
}

bool Queue::isfull() const
{
	return items == qsize;
}

int Queue::queuecount() const
{
	return items;
}

bool Queue::enqueue(const Item & item)
{
	if (isfull())
		return false;
	Node * add = new Node;
	add->item = item;
	add->next = NULL;
	items++;
	if(front == NULL)
		front = add;
	else
		rear->next = add;
	rear = add;
	return true;
}

bool Queue::dequeue(Item & item)
{
	if(front == NULL)
		return false;
	item = front->item;
	items--;
	Node * temp = front;
	front = front->next;
	delete temp;
	if(items == 0)
		rear = NULL;
	return true;
}

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

[code lang="C" title="queue.cpp"]

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.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;
	Queue line1(qs);
	Queue line2(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 temp1,temp2;
	long turnaways = 0;
	long customers = 0;
	long served = 0;
	long sum_line = 0;
	int wait_time1,wait_time2;
	wait_time1 = wait_time2 = 0;
	long line_wait = 0;
	for(int cycle = 0;cycle < cyclelimit; cycle++)
	{
		if (newcustomer(min_per_cust))
		{
			if ( line1.isfull() && line2.isfull() )
				turnaways++;
			else
			{
				customers++;
				if ( line1.isfull() )
				{
					temp2.set(cycle);
					line2.enqueue(temp2);
				}
				else
				{
					temp1.set(cycle);
					line1.enqueue(temp1);
				}
			}
		}
		if (wait_time1 <= 0 && !line1.isempty())
                {
                        line1.dequeue(temp1);
                        wait_time1 = temp1.ptime();
                        line_wait += cycle - temp1.when();
                        served++;
                }
		if (wait_time2 <= 0 && !line2.isempty())
                {
                        line2.dequeue(temp2);
                        wait_time2 = temp2.ptime();
                        line_wait += cycle - temp2.when();
                        served++;
                }
		if(wait_time1 > 0)
			wait_time1--;
		if(wait_time2 > 0)
			wait_time2--;
		sum_line += ( line1.queuecount() + line2.queuecount() );
	}

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

函数指针

今天看到了函数指针这一小结,发现自己对指针的认知还是不够深刻,特意贴下来,日后回顾。
《C++ Primer Plus》
第七章 7.19(arfupt.cpp)

#include <iostream>

const double * f1(const double ar[], int n);
const double * f2(const double [], int);
const double * f3(const double *, int);

int main()
{
	using namespace std;
	double av[3] = { 1112.3, 1542.6, 2227.9 };
//p1 指向 f1
	const  double * (*p1)(const double * ,int) = f1;
//自动声明类型
	auto p2 = f2;
	cout << "Using pointers to functions:\n";
	cout << " Address Value\n";
	cout << (*p1)(av,3) << ": " << *(*p1)(av,3) << endl;
	cout << (*p2)(av,3) << ": " << *(*p2)(av,3) << endl;
//注意()优先级大于*,*p2(av,3) == *(p2(av,3))
	cout << p2(av,3) << ": " << *p2(av,3) << endl;

//二级指针
	const double * (*pa[3])(const double * , int) = { f1,f2,f3 };
	auto pb = pa;
	cout << "\nUsing an array of pointers to functions:\n";
	cout << " Address Value\n";
	for (int i = 0;i < 3;i++)
// (*(pa+i))(av,3) == pa[i](av,3) 似乎[]优先级高于()
		cout << (*(pa + i))(av,3) << ": " << *(*(pa+i))(av,3) << endl;

	cout << "\nUsing a pointer to a pointer to a function:\n";
	cout << " Address Value\n";
	for (int i = 0;i < 3; i++)
		cout << pb[i](av,3) << ": " << *pb[i](av,3) << endl;

	cout << "\nUsing pointers to an array of pointers:\n";
	cout << " Address Value\n";
// 三级指针
	const double *(*(*pd)[3])(const double *, int ) = & pa;
	auto pc = &pa;
	const double * pdb = (*pd)[1](av,3);

	cout << (*pc)[0](av,3) << ": " << *(*pc)[0](av,3) << endl;
	cout << pdb << ": " << *pdb << endl;
	cout << (*(*pd)[2])(av,3) << ": " << *(*(*pd)[2])(av,3) << endl;
	return 0;
}

const double * f1 (const double * ar, int n)
{
	return ar;
}
const double * f2 (const double ar[] , int n)
{
	return ar+1;
}
const double * f3 (const double * ar, int n)
{
	return ar+2;
}

第七章 复习题-13

#include <iostream>
#include <cstring>
//声明一个结构体
struct applicant
{
	char name[30];
	int credit_rating[3];
};
using namespace std;

//声明一个show函数
void show(applicant *);

//声明一个empty函数
void empty(const applicant *);

//声明一个函数指针类型
typedef void (*tempty)(const applicant *);

//声明一个指向empty函数的函数指针p1
tempty p1 = empty;

//声明一个函数strscat
const char * strscat(const applicant *, const applicant *);

//声明一个函数指针p2,并指向strscat
const char * (*p2)(const applicant *,const applicant *) = strscat;

//声明一个包含5个函数指针的数组ap
tempty ap [5];

//声明一个包含10个函数指针的数组pb
const char * (*(pb[10]))(const applicant * ,const applicant *);
//同上,声明一个包含10个函数指针的数组pc
const char * (*pc[10])(const applicant * ,const applicant *);

//声明一个指向包含10个函数指针的数组的指针pa
char * (*(*pa[10]))(const applicant * ,const applicant *);

int main()
{
	struct applicant test = { "=-=.",{ 0,1,2 } };
	cout << "Use show function." << endl;
	show(&test);
	cout << "Use strscat function." << endl;
	const char * pstr = strscat(&test,&test);
	cout << pstr << endl;
//忘记添加的delete. =_=!
	delete [] pstr;
	return 0;
}
void show(struct applicant * app)
{
	cout << app->name << endl;
	for (int i = 0; i < 3; i++)
		cout << app->credit_rating[i] << endl;
	return;
}
void empty(const applicant * a)
{
	return;
}
const char * strscat(const applicant * chars1, const applicant * chars2)
{
	char pstr [20];
	strcpy(pstr,chars1->name);
	char * str = new char [40];
	strcpy(str,strcat(pstr,chars2->name));
	return str;
}

C++编程练习

题目出自《C++ Primer Plus》第5章

假设要销售《C++ For Fools》一书。请编写一个程序,输入全年中每个月的销售量(图书数量,而不是销售额)。程序通过循环,使用初始化为月份字符串的char*数组或string对象数组)逐月进行提示,并将输入的数据储存在一个int数组中。然后,程序计算数组中各元素的总数,并报告这一年的销售情况(我自定义了结构体数组一并完成第六题)。

#include <iostream>
#include <cstdio>
const int this_year = 2017;
const int years = 3;
const int per_year = 12;
struct record
{
        int  years;
        int months;
        long sales;
};
int main()
{
        using namespace std;
        record (*date)[per_year] = new record [years][per_year];
        for (int i = 0;i < years;++i)
                for (int j = 0;j < per_year; ++j)
                {
                        date[i][j].years=this_year+i;
                        date[i][j].months=j+1;
                        cout << "Please input sales for "
                                << date[i][j].years 
                                << " year "
                                << date[i][j].months
                                << " month:\n";
                        cin >> date[i][j].sales;
                }
        long long * sales_per_year = new long long [years];
        for (int i = 0;i < years; ++i)
        {
                for (int j = 0;j < per_year; ++j)
                        sales_per_year[i] += date[i][j].sales;
                cout << this_year + i  
                        << " year had been sale "
                        << sales_per_year[i] 
                        << " books." << endl;
        }       
        return 0;
}

编写一个程序,它使用一个char数组和循环来每次读取一个单词,直到用户输入done为止。随后,该程序指出用户输入了多少个单词(不包括done在内)。下面是该程序的运行情况:

Enter words (to sto p , type the word done) :</span>
anteater birthday category dumpster 
envy finagle geometry done for sure
You entered a total of 7 words.

您应在程序中包含头文件cstring,并使用函数StrCmp()来进行比较测试

#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
int main()
{
	char * ch = new char;
	char * word = new char [100];
	char * string = new char [100];
	int *pcw = new int ;
	int *pcc = new int ;
	*pcc=*pcw=0;
//确认前面的一个字符不为空
	bool empty=true;
	while ( strcmp(word,"done") )
	{
		*ch=getchar();
		if ( *ch == EOF || *ch == ' ' || *ch == '\n' )
		{	
			if ( empty )
			{
				continue;
			}
			strcpy(word,string);
			string[0]='\0';
			*pcc=0;
			if ( word[0] != ' ' || word[0] != '\n' || word[0] != EOF )
				++*pcw;
			empty=true;
			continue;
		}
		string[*pcc]=*ch;
		empty=false;
		string[(*pcc)+1]='\0';
		(*pcc)+=1;
	}
	cout << "You entered a total of " 
		<< (*pcw)-1 
		<< " words."
		<< endl;
	return 0;
}

题目出自《C++ Primer Plus》第6章
编写一个程序,它毎次读取一个单词,直到用户只输入q。然后, 该程序指出有多少个单词以元音打头,有多少个单词以辅咅打头,还有多少个单词不属于这两类。为此,力法之一睡是,使用isalpha()来区分以字母和其他字符打头的单词,然后对于通过isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序的运行情况如下:

Enter words (q to quit ) :
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words be ginning with vowels 
4 words be ginning with consonants
2 other

*需要判断每个字符的前面一个字符和后面一个字符

#include <iostream>
#include <cctype>
#include <cstdio>
using namespace std;
int main()
{
	cout << "Enter words (q to quit):" << endl;
	char ch;
	bool empty = true;
	int vowels,consonants,others;
	others=vowels=consonants=0;
	while ( ch = cin.get() )
	{
		cin.clear();
		if (empty)
		{
			if ( isalpha(ch) )
			{
				if ( ch == 'q' )
				{
					char temp;
					temp=cin.get();
					if (temp == '\n' || temp == ' ' || temp == EOF)
					{	
						empty = true;
						break;
					}
					else
					{	
						++consonants;
						empty = false;
					}
				}
				else if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u')
				{
						++vowels;
						empty = false;
				}
				else
				{
					++consonants;
					empty = false;
				}
			}
			else
			{
				++others;
				char temp;
				if ((temp = cin.get()) != '\n' || temp != ' ' || temp != EOF)
				{
					empty = false;
				}
				else
				{
					empty = true;
				}
			}
		}
		else if (ch == '\n' || ch == ' ' || ch == EOF)
			empty = true;
		else
		{
			empty = false;
			continue;
		}
	}
	cout << vowels << " words beginning with vowels" << endl;
	cout << consonants << " words begining with consonants" << endl;
	cout << others << " others" << endl;
	return 0;
}

题目出自《C++ Primer Plus》第8章
函数重载(多态),函数模板

#include <iostream>
template <typename T> void ShowArray(T arr[],int n);
template <typename T> void ShowArray(T * arr[],int n);
int SumArray(int * ,int n);
double SumArray(double * *,int n);
struct debts
{
	char name[50];
	double amount;
};
int main()
{
	using namespace std;
	int things[6] = { 13,31,103,301,310,130 };
	struct debts mr_E[3] = 
	{
		{ "Ima Wolfa", 2400.0 },
		{ "Ura Foxe", 1300.0 },
		{ "Iby Stout", 1800.0 }
	};
	double * pd[3];
	for (int i = 0; i < 3; i++)
		pd[i] = &mr_E[i].amount;
	cout << "Listing Mr. E's counts of things:\n";
	ShowArray(things,6);
	cout << "Listing Mr. E's debts:\n";
	ShowArray(pd,3);
	cout << SumArray(things,6) << endl;
	cout << SumArray(pd,3) << endl;
	return 0;
}
template <typename T> void ShowArray(T arr [], int n)
{
	using namespace std;
	cout << "template A\n";
	for(int i = 0;i < n;i++)
		cout << arr[i] << ' ';
	cout << endl;
	return ;
}
template <typename T> void ShowArray(T * arr [] ,int n)
{
	using namespace std;
	cout << "template B\n";
	for(int i = 0;i < n;i++)
		cout << *arr[i] << ' ';
	cout << endl;
	return ;
}
int SumArray(int * arr, int n)
{
	int result = 0;
	for (int i = 0;i < n;i++)
		result +=  arr[i];
	return result;
}
double SumArray(double * * arr,int n)
{
	double result = 0;
	for(int i = 0;i < n;i++)
		result += *arr[i];
	return result;
}

陆续更新