C++ Primier Exercises

第八章缺失,当时写完忘记保存就关机了。对不起。我也很懊悔!

1 开始

1.1

Process exited after 3.368 seconds with return value 0

#include
int main()
{
	std::cout<<"Enter two numbers:"<>v1>>v2;
	std::cout<<"The sum of "<

1.2

Process exited after 3.514 seconds with return value 4294967295

#include
int main()
{
	std::cout<<"Enter two numbers:"<>v1>>v2;
	std::cout<<"The sum of "<

1.3

#include
int main()
{
	std::cout<<"Hello world."<

1.4

#include
int main()
{
	std::cout<<"Enter two numbers:"<>v1>>v2;
	std::cout<<"The multiplication of "<

1.6

去除v1,v2后多余的分号。

1.9

#include
using namespace std;
int main()
{
	int n=50;
	int sum=0;
	while(n<=100){		
		sum+=n;
		n++;
	}
	cout<

1.10

#include
using namespace std;
int main()
{
	int num=10;
	while(num>=0){
		cout<

1.11

#include
using namespace std;
int main()
{
	cout<<"Please enter two number:"<>m;
	cin>>n;
	int num=n;
	while(num<=m)
	{
		cout<

1.12

初始化语句为:int i=-100;

循环条件为:i<=100;

表达式为:++i;

完成的功能为:-100~100求和

sum=0;

1.13

#include
using namespace std;
int main()
{
	int n=50;
	int sum=0;
	for(;n<=100;n++){		
		sum+=n;
	}
	cout<
#include
using namespace std;
int main()
{
	int num=10;
	for(;num>=0;num--){
		cout<
#include
using namespace std;
int main()
{
	cout<<"Please enter two number:"<>m;
	cin>>n;
	int num=n;
	for(;num<=m;num++){
		cout<

1.15

#include
using namespace std;
int main()
{
	int num=0;
	int sum=0;
	while(cin>>num){
		sum+=num;
	}
	cout<

这个问题之前好像在群里讨论过,原来C++ primer里就有练习

1.19

#include
using namespace std;
int main()
{
	cout<<"Please enter two number:"<>m;
	cin>>n;
	if(m>=n){
		int num=n;
		while(num<=m)
		{
			cout<

2 变量和基本类型

2.3

u2 - u = 42 - 10 = 32

u - u2 = 10 - 42 = -32 = 4294967264(unsigned类型转换)

i2 - i = 42 - 10 =32

i - i2 =10 - 42 = - 32

i - u = 0

u - i = 0

2.8

#include
using namespace std;
int main()
{
	cout<<"2M\n";
	cout<<"2\tM\n";
}

2.18

#include
using namespace std;
int main()
{
	int i=1;
	int *p=&i;
	cout<<*p<<" "<

output:

1 0x6dfe84
2 0x6dfe80
3 0x6dfe80

2.19

指针:

  • 对象,允许赋值和拷贝
  • 在生命周期内可以先后指向几个不同的对象
  • 无需在定义时赋值,但需要被初始化

引用:

  • 必须被初始化
  • 不是对象,

2.36

debug

#include
using namespace std;
int main()
{
	int a = 3, b = 4;
	decltype(a)c = a;
	decltype((b))d = a;
	++c;
	++d;
	cout << a << " " << b << " " << c << " " << d << " " << endl;
}

2.37

debug

#include
using namespace std;
int main()
{
	int a = 3, b = 4;
	decltype(a)c = a;
	decltype(a = b)d = a;
	cout << a << " " << b << " " << c << " " << d << " " << endl;
}

2.38

debug

#include
using namespace std;
int main()
{
	int a = 3, b = 4;
	auto c = a;
	decltype (a) c = a;
	auto d = b;
	decltype((b))d = b;
}

2.41

#include
#include
using namespace std;
class Sales_data
{
public:
	string bookNo;
	unsigned units_sold = 0;
	double revenue = 0.0;
};
int main()
{
	Sales_data data1;
	Sales_data data2;
	double price = 0.0;
	cout << "please input the data1,data2 and the price!" << endl;
	cin >> data1.bookNo >> data2.bookNo >> price;
	data1.revenue = data1.units_sold * price;
	data2.revenue = data2.units_sold * price;
	cout << "data1 revenue:" << data1.revenue << endl;
	cout << "data2 revenue:" << data2.revenue << endl;
	return 0;
}

2.42

#include
#include
using namespace std;
class Sales_data
{
public:
	string bookNo;
	unsigned units_sold = 0;
	double revenue = 0.0;
};
int main()
{
	Sales_data data1;
	Sales_data data2;
	double total_revenue = 0.0;
	double price = 0.0;
	double price1 = 0.0;
	double price2 = 0.0;
	cout << "please input the data1,data2 and the price!" << endl;
	cin >> data1.bookNo >>price1>> data2.bookNo >> price2;
	cout << "enter your books' units_sold:" << endl;
	cin >> data1.units_sold >> data2.units_sold;
	data1.revenue = data1.units_sold * price1;
	data2.revenue = data2.units_sold * price2;
	total_revenue = data1.revenue + data2.revenue;
	price = total_revenue / (data1.units_sold + data2.units_sold);
//	cout << "data1 revenue:" << data1.revenue << endl;
//	cout << "data2 revenue:" << data2.revenue << endl;
	cout << "the average price is : " << price;
	return 0;
}

2.43

#include
#include
using namespace std;
class Sales_data
{
public:
	string bookNo;
	unsigned units_sold = 0;
	double revenue = 0.0;
	friend bool operator == (Sales_data&, Sales_data&);
};
int main()
{
	Sales_data sumdata, data;
	double aprice = 0.0;
	double sumprice = 0.0;
	double price = 0.0;
	unsigned sumunit_sold = 0;
	cout << "please input the first data:(bookNO,units_sold,revenue)" << endl;
	cin >> sumdata.bookNo >> sumdata.revenue >> sumdata.units_sold;
	sumprice = sumdata.revenue * sumdata.units_sold;
	sumunit_sold = sumdata.units_sold;
	cout << "please input the next data: " << endl;
	while (cin >> data.bookNo >> data.revenue >> data.units_sold)
	{
		if (data.bookNo == sumdata.bookNo)
		{
			sumprice += data.revenue * data.units_sold;
			sumunit_sold += data.units_sold;
			
		}
		cout << "please input the next data: " << endl;
	}
	aprice = sumprice / sumunit_sold;
	cout << "The average price is : " << aprice;
}
bool operator == (Sales_data& data1, Sales_data& data2)
{
	return data1.bookNo == data2.bookNo && data1.revenue == data2.revenue && data1.units_sold == data2.units_sold;
}

2.44

#include
#include
using namespace std;
class Sales_data
{
public:
	string bookNo;
	unsigned units_sold = 0;
	double revenue = 0.0;
	friend bool operator == (Sales_data&, Sales_data&);
};
int main()
{
	Sales_data sumdata, data;
	double aprice = 0.0;
	double sumprice = 0.0;
	double price = 0.0;
	unsigned sumunit_sold = 0;
	int cnt = 0;
loop:
	cout << "please input the first data:(bookNO,units_sold,revenue)" << endl;
	cin >> sumdata.bookNo >> sumdata.revenue >> sumdata.units_sold;
	sumprice = sumdata.revenue * sumdata.units_sold;
	sumunit_sold = sumdata.units_sold;
	cout << "please input the next data: " << endl;
	cnt ++;
	while (cin >> data.bookNo >> data.revenue >> data.units_sold)
	{
		if (data.bookNo == sumdata.bookNo)
		{	
			sumprice += data.revenue * data.units_sold;
			sumunit_sold += data.units_sold;
			cout << "please input the next data: " << endl;
			cnt++;
		}
		else
		{
			aprice = sumprice / sumunit_sold;
			sumprice = sumdata.revenue * sumdata.units_sold;
			sumunit_sold = sumdata.units_sold;		
			cout << "The same BookNo is: " << data.bookNo << endl << "The average price is : " << aprice << endl;
			cout << "The number of these books is: " <

3 字符串、向量和数组

3.2

#include
#include
using namespace std;
int main()
{
    string s;
    // while(getline(cin,s))
    // {
    //     cout<>s){
        cout<

3.4

#include
#include
using namespace std;
int main()
{
    string s,k;
    cout<<"please input the string s:"<>s;
    cout<<"please input the string k:"<>k;
    string max;
    max=s;
    if(max>k){
        cout<>p;
    cout<<"please input the string q:"<>q;
    string maxx=p;
    if(max!=q&&max>q)
    {
        cout<

3.5

#include
#include
using namespace std;
int main()
{
    string s;
    static string temp;
    while(getline(cin,s))
    {
        temp+=s;
        cout<
#include
#include
using namespace std;
int main()
{
    string s;
    static string temp;
    while(cin>>s)
    {
        temp+=s;
        temp+=" ";
        cout<

3.6

#include
#include
using namespace std;
int main()
{
    string t;
    cout<<"please input a string: "<>t;
    for(auto s:t)
    {
        s='X';
        cout<

3.8

#include
#include
using namespace std;
int main()
{
    string t;
    cout<<"please input a string: "<>t)
    {
        int cnt=1;
        while(cnt<=t.size())
        {
            cout<<"X";
            cnt++;
        }
    }
    cout<
#include
#include
using namespace std;
int main()
{
    string t;
    cout<<"please input a string: "<>t;
    for(int i=0;i

3.10

#include
#include
using namespace std;
int main()
{
    string t;
    cout<<"please input a string: "<>t;
    for(auto s:t)
    {
        if(!ispunct(s))
        {
            cout<

3.14

#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    vector nums;
    int s;
    while(cin>>s)
    {
        nums.push_back(s);
    }
    for(int i=0;i

3.15

#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    string s;
    vector nums;
    while(cin>>s)
    {
        nums.push_back(s);
        cout<

3.16

#include
#include
#include
using std::vector;
using namespace std;
void test(vector v);
void test2(vector v);
int main()
{
    vector v1;
    vector v2(10);
    vector v3(10,42);
    vector v4{10};
    vector v5{10,42};
    vector v6{10};
    vector v7{10,"hi"};
    int temp=0;
    cout<<"enter which vector do you wanna select:(1~7)"<>temp;
    switch(temp)
    {
        case 1:cout<<"vector v1:"< v)
{
    cout<<"size= "< v)
{
    cout<<"size= "<

3.17

#include
#include
#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    vector s;
    string t;
    // int num[20];
    // for(int i=0;cin>>t;i++)
    while(cin>>t)
    {
        // num[i]=t.size();
        s.push_back(t);
        if(t=="quit")
        {
            break;
        }

    }
    cout<

3.19

#include
#include
using std::vector;
using namespace std;
void printElement(vector v);
int main()
{
	vector ivec1(10,42);
	vector ivec2{ 42,42,42,42,42,42,42,42,42,42 };
	vector ivec3;
	for (int i = 0; i!= 10; i++)
	{
		ivec3.push_back(42);
	}
	cout << "ivec1:" << endl;
	printElement(ivec1);
	cout << "ivec2:" << endl;
	printElement(ivec2);
	cout << "ivec3:" << endl;
	printElement(ivec3);

}
void printElement(vector v)
{
	for (int i = 0; i < 10; i++)
	{
		cout << v[i]<<" ";
	}
	cout << endl;
}

3.20

#include
#include
#include
#include
#include
using std::vector;
using namespace std;
const int N=10;
void printElement(vector v);
int main()
{
    int j=0;
    int arr[N]={0};
    int Arr[N]={0};
    vector nums;
    vector Nums;
    cout<<"enter the element:"<>arr[i];
        nums.push_back(arr[i]);
    }
    for(int i=0;i v)
{
	for (int i = 0; i < N/2; i++)
	{
		cout << v[i]<<" ";
	}
	cout << endl;
}
#include
#include
#include
#include
#include
using std::vector;
using namespace std;
void printElement(vector v);
const int N=10;
int main()
{
    
    int j=0;
    int arr[N]={0};
    int Arr[N]={0};
    vector nums;
    vector Nums;
    cout<<"enter the element:"<>arr[i];
        nums.push_back(arr[i]);
    }
    for(int i=0;i v)
{
	for (int i = 0; i < N/2; i++)
	{
		cout << v[i]<<" ";
	}
	cout << endl;
}

3.21

#include
#include
#include
using std::vector;
using namespace std;
void test(vector v);
void test2(vector v);
int main()
{
    vector v1;
    vector v2(10);
    vector v3(10,42);
    vector v4{10};
    vector v5{10,42};
    vector v6{10};
    vector v7{10,"hi"};
    int temp=0;
    cout<<"enter which vector do you wanna select:(1~7)"<>temp;
    switch(temp)
    {
        case 1:cout<<"vector v1:"< v)
{
    cout<<"size= "< v)
{
    cout<<"size= "<empty();it++)
    {
        cout<<"element"<<":"<<*it<

3.22

#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    string s;
    vector text;
    while(cin>>s)
    {
        text.push_back(s);
        if(s=="quit")
        {
            break;
        }
    }
    for(auto it=text.begin();it!=text.end()&&!it->empty();++it)
    {
        for(auto &c:(*it))
        {
            c=toupper(c);
        }
        cout<<*it<

3.23

#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    int arr[10];
    vector<int> nums;
    for(int i=0;i<10;i++)
    {
        cin>>arr[i];
        nums.push_back(arr[i]);
    }
    for(auto it=nums.begin();it!=nums.end();it++)
    {

            cout<<2*(*it)<<" ";
    }
}

3.24

#include
#include
#include
#include
#include
using std::vector;
using namespace std;
void printElement(vector v);
const int N=10;
int main()
{
    int n=0;
    vector nums;
    vector Nums;
    cout<<"please enter the element:"<>n;
        nums.push_back(n);
    }
    for(auto it=nums.begin();it+1!=nums.end();it++)
    {
        cout<<*it+*(it+1)<<" ";
    }
    cout<
#include
#include
#include
#include
#include
using std::vector;
using namespace std;
void printElement(vector v);
const int N=10;
int main()
{
    int n=0;
    vector nums;
    vector Nums;
    cout<<"please enter the element:"<>n;
        nums.push_back(n);
    }
    auto It=nums.end()-1;
    for(auto it=nums.begin();it+1!=nums.end();it++,It--)
    {
        cout<<*it+*It<<" ";
    }
    cout<

3.25

#include
#include
#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    vector score(11,0);
    unsigned grade;
    auto it=score.begin();
    int cnt=1;
    while(cin>>grade)
    {
        cnt++;
        if(grade<=100)
        {
            ++*(it+grade/10);
        }
        if(cnt==11)
        {
            break;
        }
    }
    for(int i=0;i<11;i++)
    {
        if(i<10)
        {
            cout<<"score under "<<(i+1)*10<<" "<

3.31

#include
#include
#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    int arr[10];
    for(int i=0;i<10;i++)
    {
        arr[i]=i;
        cout<

3.32

#include
#include
#include
#include
#include
using std::vector;
using namespace std;
int main()
{
    vector arr;
    for(int i=0;i<10;i++)
    {
        arr.push_back(i);
        cout<

3.35

#include
#include
#include
#include
#include
using namespace std;
int main()
{
    
    int arr[10];
    int *b=begin(arr);
    int* e = end(arr);
    for (; b != e; b++)
    {
        *b = 0;
        cout << *b << " ";
    }
}

3.36

#include
#include
#include
#include
#include
using namespace std;
int main()
{
    const int N=10;
    int arr1[N];
    int arr2[N];
    cout<<"please enter the first array :"<>*b1;
    }
    cout<<"please enter the second array :"<>*b2;
    }
    if(arr1[N]==arr2[N])
    {
        cout<<"these two arries are the same."< vec1;
    vector vec2;
    int vec;
    int Vec;
    cout<<"please enter the first vector :"<>vec)
    {
        vec1.push_back(vec);
        if(vec==0)
        {
            break;
        }
    }
    cout<<"please enter the second vector :"<>Vec)
    {
        vec2.push_back(Vec);
    }
    if(vec1==vec2)
    {
        cout<<"these two vector are the same."<

3.39

#include
#include
#include
#include
#include
using namespace std;
int main()
{
    string s1;
    string s2;
    while(cin>>s1)
    {
        if(s1=="quit")
        {
            break;
        }
    }
    while(cin>>s2)
    {
        if(s2=="quit")
        {
            break;
        }       
    }
    if(s1==s2)
    {
        cout<<"same"<s2)
    {
        cout<<"s1 larger"<
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    char ca[10];
    char Ca[10];
    cout<<"enter the elements in ca:"<>ca[i];
    }
    cout<<"enter the elements in Ca:"<>Ca[i];
    }
    if(strcmp(ca,Ca)>0)
    {
        cout<<"ca larger"<

2.40

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    char ca1[6]={"abcde"};
    char ca2[6]={"fghij"};
    char ca3[12];
    strcpy(ca3,ca1);
    strcat(ca3,"");
    strcat(ca3,ca2);
    cout<

3.41

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int arr[10];
    cout<<"enter the elements in arr:"<>arr[i];
    }
    vector vec(begin(arr),end(arr));
    for(auto it=vec.begin();it!=vec.end();it++)
    {
        cout<<*it;
    }
}

3.42

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    vector vec;
    for(int i=0;i<10;i++)
    {
        vec.push_back(i);
    }
    int arr[10];
    for(auto it=begin(arr);it!=end(arr);it++)
    {
        *it=vec[it-begin(arr)];
    }
    for(auto i:arr)
    {
        cout<

3.43

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int ia[3][4]={0,1,2,3,4,5,6,7,8,9,10,11,};
    for(const int (&p)[4]:ia)
    {
        for(int q:p)
        {
            cout<

3.44

#include
#include
#include
#include
#include
#include
using namespace std;
using int_array=int[4];
typedef int int_array[4];
int main()
{
    int ia[3][4]={0,1,2,3,4,5,6,7,8,9,10,11,};
    for(const int_array &p:ia)
    {
        for(int q:p)
        {
            cout<

3.45

#include
#include
#include
#include
#include
#include
using namespace std;
using int_array=int[4];
typedef int int_array[4];
int main()
{
    int ia[3][4]={0,1,2,3,4,5,6,7,8,9,10,11,};
    for(auto &p:ia)
    {
        for(auto q:p)
        {
            cout<

4.表达式

4.2

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int n;
    cout<<"enter a number to judge:"<>n;
    if(n%2==0)
    {
        cout<<"even number"<

4.10

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int n;
    while(cin>>n&&n!=42)
    {
        cout<

4.11

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int a,b,c,d;
    cout<<"enter the 'a','b','c','d':"<>a>>b>>c>>d;
    if(a>b&&b>c&&c>d)
    {
        cout<<"text successfully"<

4.21

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    vector vec;
    int num;
    while(cin>>num)
    {
        vec.push_back(num);
        if(num==0)
        {
            break;
        }
    }
    for(int i=0;i

4.22

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int num;
    vector score;
    cout<<"enter the score while your score more than 0:"<>num)
    {
        score.push_back(num);
        if(num==-1)
        {
            break;
        }
    }
    for(int i=0;i90)?"high pass":(score[i]>75)?"low pass":(score[i]>60)?"pass":"fail");
    }
}
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int num;
    vector score;
    cout<<"enter the score while your score more than 0:"<>num)
    {
        score.push_back(num);
        if(num==-1)
        {
            break;
        }
    }
    for(int i=0;i=90){
            cout<<"high pass"<=75){
            cout<<"low pass"<=60){
            cout<<"pass"<

4.23

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    string s="word";
    string p1=s+(s[s.size()-1]=='s'?"":"s");
    cout<

4.28

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{

	cout << "bool " << sizeof(bool) << endl;
	cout << "char " << sizeof(char) << endl;
	cout << "short " << sizeof(short) << endl;
	cout << "int " << sizeof(int) << endl;
	cout << "long " << sizeof(long) << endl;
	cout << "long long " << sizeof(long long) << endl;
	cout << "float " << sizeof(float) << endl;
	cout << "double " << sizeof(double) << endl;
	cout << "long double " << sizeof(long double) << endl;
}

4.31

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int n;
    vector ivec;
    while(cin>>n)
    {
        ivec.push_back(n);
        if(n==-1)
        {
            break;
        }
    }
    vector::size_type cnt=ivec.size();
    for(vector::size_type ix=0;ix!=ivec.size();ix++,cnt--)
    {
        ivec[ix]=cnt;
        cout<

4.36

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int i=2;
    double d=2.2;
    i*=static_cast(d);
    cout<

5.语句

5.3

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int sum=0;
    int val=1;
    while(val<=10) sum+=val,++val;
    cout<<"Sum of 1 to 10 inclusive is "<

5.5

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    const vector score={"F","D","C","B","A","A++"};
    string lettergrade;
    int grade;
    cout<<"enter the score:"<>grade&&grade>0)
    {
        if(grade<60)
        {
            lettergrade=score[0];
        }
        else
        {
            lettergrade=score[(grade-50)/10];
        }
        cout<

5.6

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    const vector score={"F","D","C","B","A","A++"};
    string lettergrade;
    int grade;
    cout<<"enter the score:"<>grade&&grade>0)
    {
        lettergrade=(grade<60)?score[0]:score[(grade-50)/10];
        cout<

5.9

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    unsigned aCht=0,eCht=0,iCht=0,oCht=0,uCht=0,Cht=0;
    char ch;
    while(cin>>ch&&ch!='0')
    {
        if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') Cht++; 
        if(ch=='a') aCht++;
        else if(ch=='e') eCht++;
        else if(ch=='i') iCht++;
        else if(ch=='o') oCht++;
        else if(ch=='u') uCht++;
    }
    cout<<"a: "<

5.10

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    unsigned aCht=0,eCht=0,iCht=0,oCht=0,uCht=0,Cht=0;
    char ch;
    while(cin>>ch&&ch!='0')
    {
        if(ch>='A'&&ch<='Z') ch=ch+32;
        if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') Cht++; 
        if(ch=='a') aCht++;
        else if(ch=='e') eCht++;
        else if(ch=='i') iCht++;
        else if(ch=='o') oCht++;
        else if(ch=='u') uCht++;
    }
    cout<<"a: "<

5.11

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    unsigned aCht=0,eCht=0,iCht=0,oCht=0,uCht=0,Cht=0,bCht=0,tCht=0,nCht=0;
    char ch;
    cin>>noskipws;
    while(cin>>ch&&ch!='0')
    {
        if(ch>='A'&&ch<='Z') ch=ch+32;
        if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') Cht++; 
        if(ch=='a') aCht++;
        else if(ch=='e') eCht++;
        else if(ch=='i') iCht++;
        else if(ch=='o') oCht++;
        else if(ch=='u') uCht++;
        else if(ch=='\40') bCht++;
        else if(ch=='\t') tCht++;
        else if(ch=='\n') nCht++;
    }
    cout<<"a: "<

5.12

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    unsigned aCht=0,eCht=0,iCht=0,oCht=0,uCht=0,Cht=0,bCht=0,tCht=0,nCht=0,doubleCht=0;
    char ch;
    cin>>noskipws;
    while(cin>>ch&&ch!='0')
    {
        if(ch>='A'&&ch<='Z') ch=ch+32;
        if(ch=='f'){
            cin>>ch;
            if(ch=='l'||ch=='i')
            {
                doubleCht++;
            }
        }
        if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') Cht++; 
        if(ch=='a') aCht++;
        else if(ch=='e') eCht++;
        else if(ch=='i') iCht++;
        else if(ch=='o') oCht++;
        else if(ch=='u') uCht++;
        else if(ch=='\40') bCht++;
        else if(ch=='\t') tCht++;
        else if(ch=='\n') nCht++;

    }
    cout<<"a: "<

5.14

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{

    string s;
    string t;
    static string p;
    cout<<"enter a string: "<>s&&s!="quit")
    {
        if(s==t)
        {
            cnt++;
            p=t;
        }
        else
        {
            if(cnt>max_cnt)
            {
                max_cnt=cnt;
                p=t;
                // cout<1)
    {
        cout<<"the count is "<

5.17

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    vector vec1;
    vector vec2;
    int arr1[N];
    int arr2[N];
    int i=0;
    cout<<"enter the arr1:"<>arr1[i])
    {
        if(arr1[i]==-1)
        {
            break;
        }
        vec1.push_back(arr1[i]);
        i++;

    }
    cout<<"enter the arr2:"<>arr2[j])
    {
        if(arr2[j]==-1)
        {
            break;
        }
        vec2.push_back(arr2[j]);
        j++;

    }
    if(vec1.size()>=vec2.size())
    {
        for(int m=0;m

5.19

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    string s;
    string t;
    vector string2;
    do{
        cout<<"please enter string 1:"<

5.20

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    string s;
    string pre_s;
    // cin>>noskipws;
    cout<<"please enter some words:"<>s&&s!="quit"){
        
        if(s==pre_s)
        {
            pre_s=s;
            cout<

5.21

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    string s;
    string pre_s;
    // cin>>noskipws;
    cout<<"please enter some words:"<>s&&s!="quit"){
        if(!isupper(s[0])) continue;
        if(s==pre_s)
        {
            pre_s=s;
            cout<

5.22

未定义函数

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    do{
        int sz=get_size();
    }while(sz>0);
    cout<

5.23

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    int m;
    int n;
    cout<<"enter two number:"<>m>>n;
    cout<

5.24

#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    int m;
    int n;
    cout<<"enter two number:"<>m>>n;
    if(n==0)
    {
        throw runtime_error("the second number couldn't be zero!");
    }
    cout<

what():the second number couldn’t be zero!

5.25

#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int N=10;
int main()
{
    int m;
    int n;
    cout<<"enter two number:"<>m>>n)
    {
        try{
            if(n==0)
            {
                throw runtime_error("the second number couldn't be zero!");
            }
            cout<>c;
            if(!cin||c=='n') break;
            else continue;
        }
    }
}

6.函数

6.4

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int fact(int val);
int main()
{
    int n,m;
    cout<<"please input a number:"<>n;
    m=fact(n);
    cout<=1;i--)
    {
        val*=i;
    }
    return val;
}

6.5

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int myabs(int val);
int main()
{
    int n,m;
    cout<<"please input a number:"<>n;
    m=myabs(n);
    cout<<"the abs of the number is:"<=0) return val;
    else return (-val);
}

6.6

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int test(int val);
int main()
{
    int n;
    cout<<"please input the number:"<>n;
    cout<>m;
    for(int i=0;i<5;i++)
    {
        m+=val;
    }
    return m;
}

6.7

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int test();
int main()
{
    int n;
    cout<<"please input the time:"<>n;
    for(int i=1;i

6.8

#ifndef CHAPTER6_H
#define CHAPTER6_H

int fact(int val);

#endif

6.9

fact.cc:

#include
#include"Chapter6.h"
using namespace std;
int fact(int val)
{
    int i=val-1;
    for(;i>=1;i--)
    {
        val*=i;
    }
    return val;
}

factmain.cc:

#include
#include"Chapter6.h"
using namespace std;
int main()
{
    int n,m;
    cout<<"please input a number:"<>n;
    m=fact(n);
    cout<

Chapter6.h:

#ifndef CHAPTER_6_H
#define CHAPTER_6_H

int fact(int val);

#endif

makefile:

A:fact.o factmain.o
	g++ -o A fact.o factmain.o
factmain.o:factmain.cc Chapter6.h
	g++ -c factmain.cc
fact.o:fact.cc Chapter6.h
	g++ -c fact.cc

TERMINAL:

~$ make
~$ ./A

6.10

#include
#include
#include
#include
#include
#include
#include
using namespace std;
void sort(int *p,int *q);
int main()
{
    int m,n;
    cout<<"please input two numbers which wanna be sorted:"<>m>>n;
    sort(&m,&n);
    cout<<"the sorted result: "<

6.11

#include
#include
#include
#include
#include
#include
#include
using namespace std;
void reset(string &t);
int main()
{
    string s;
    cout<<"enter a string which you wanna be reset: "<>s;
    reset(s);
    cout<

6.12

#include
#include
#include
#include
#include
#include
#include
using namespace std;
void sort(int &p,int &q);
int main()
{
    int m,n;
    cout<<"please input two numbers which wanna be sorted:"<>m>>n;
    sort(m,n);
    cout<<"the sorted result: "<

6.17

#include
#include
#include
#include
#include
#include
#include
using namespace std;
void upperJUdge(const string s);
void lowerSet(string &s);
int main()
{
    string s;
    cout<<"please enter a string to operate: "<>s;
    upperJUdge(s);
    lowerSet(s);

}
void upperJUdge(const string s)
{
    for(auto c:s)
    {
        if(isupper(c)){
        cout<<"this string has some upper!"<

6.21

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int compareInt(int m,int *p);
int main()
{
    int m,n;
    cout<<"please input two numbers: "<>m>>n;
    cout<<"the bigger one: "<=*p) return m;
    else return *p;
}

6.22

#include
#include
#include
#include
#include
#include
#include
using namespace std;
void sortInt(int *&p,int *&q);
int main()
{
    int m;
    int n;
    cout<<"please input two numbers: "<>m>>n;
    int *p=&m;
    int *q=&n;
    cout<<"the point: "<

6.23

#include
#include
#include
#include
#include
#include
#include
using namespace std;
void print1(const int *pi);
void print2(const int *beg,const int *end);
void print3(const int ia[],size_t size);
void print4(const int (&pi)[2]);
int main()
{
    int i=0,j[2]={0,1};
    print1(&i);
    print2(begin(j),end(j));
    print3(j,end(j)-begin(j));
    print4(j);
}
void print1(const int *pi)
{
    cout<<*pi<

6.25

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main(int argc,char *argv[])
{
    const string s1=argv[1];
    const string s2=argv[2];
    cout<<"the result: "<

TERMINAL:

~$ ./text abc def
the result: abcdef

6.26

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main(int argc,char *argv[])
{
    string s;
    for(int i=0;i!=argc;i++)
    {
        s+=string(argv[i])+" ";
    }
    cout<

TERMINAL:

~$ ./text -d -o ofile data0
./text -d -o ofile data0

6.27

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int sumList(initializer_list list);
int main(int argc,char *argv[])
{
    int n;
    n=sumList({1,2,3});
    cout< list)
{
    int sum=0;
    for(auto elem:list)
    {
        sum+=elem;
    }
    return sum;
}

6.30

text.cpp: In function ‘bool str_subrange(const string&, std::string)’:
text.cpp:19:13: error: return-statement with no value, in function returning ‘bool’ [-fpermissive]
   19 |             return ;
      |             ^~~~~~
make: *** [makefile:8:text] 错误 1

6.33

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void printVector(vector::const_iterator begin,vector::const_iterator end);
int main(int argc,char *argv[])
{
    int a;
    vector vec;
    while(cin>>a)
    {
        if(a==-1) break;
        vec.push_back(a);
    }
    printVector(vec.begin(),vec.end());
}
void printVector(vector::const_iterator begin,vector::const_iterator end)
{
    if(begin!=end)
    {
        cout<<*begin<<" ";
        return printVector(++begin,end);
    }
    else
    {
        return;
    }
}

6.38

#include
using namespace std;
int odd[]={1,3,5,7,9};
int even[]={0,2,4,6,8};
decltype(odd) &arrptr(int i)
{
    return (i%2)? odd:even;
}
int main()
{
    int n;
    cin>>n;
    int *arr=arrptr(n);
    for(int i=0;i<5;i++)
    {
        cout<

6.42

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
string make_plural(size_t ctr,const string &word,const string &ending="s");
int main(int argc,char *argv[])
{
    cout<1) ? word + ending : word;
}

6.44

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
inline bool isShorter(const string &s1,const string &s2)
{
    return s1.size()

6.47

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void printVector(vector::const_iterator begin,vector::const_iterator end);
int main(int argc,char *argv[])
{
    int a;
    vector vec;
    while(cin>>a)
    {
        if(a==-1) break;
        vec.push_back(a);
    }
    printVector(vec.begin(),vec.end());
}
void printVector(vector::const_iterator begin,vector::const_iterator end)
{
    // #ifndef NDEBUG
        cerr<

6.54

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int test(int n,int m);
int main(int argc,char *argv[])
{
    using p1=decltype(test)*;
    using p2=decltype(test);
    typedef decltype(test)* p3;
    using p4=int(*)(int m,int n);
    using p5=int(int m,int n);
    typedef int(*p6)(int a,int b);
    vector vec1;
    vector vec2;
    vector vec3;
    vector vec4;
    vector vec5;
    vector vec6; 
}
int test(int n,int m)
{
    return m+n;
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int test(int n,int m);
int main(int argc,char *argv[])
{
    vector vec{test};
    for(auto &elem:vec)
    {
        cout<

6.56

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int add(int m,int n);
int subtract(int m,int n);
int multiply(int m,int n);
int divide(int m,int n);
int main(int argc,char *argv[])
{
    vector vec{add,subtract,multiply,divide};
    for(auto &elem:vec)
    {
        cout<

7 类

7.1

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
struct Sales_data
{
    string bookNo;
    unsigned units_sold =0;
    double revenue=0.0;
};
int main(int argc,char *argv[])
{
    Sales_data total;
    double totalprice;
    if(cin>>total.bookNo>>total.units_sold>>totalprice)
    {
        total.revenue=total.units_sold*totalprice;
        Sales_data trans;
        double transprice;
        while(cin>>trans.bookNo>>trans.units_sold>>transprice)
        {
            trans.revenue=trans.units_sold*transprice;
            if(total.bookNo==trans.bookNo)
            {
                total.units_sold+=trans.units_sold;
                total.revenue+=trans.revenue;
            }
            else
            {
                cout<

7.2

#ifndef SALES_DATA_H
#define SALES_DATA_H

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Sales_data
{
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
private:
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
};
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}


#endif SALES_DATA_H

7.3

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Sales_data
{
public:
    string isbn()const{return bookNo;}
    Sales_data& combine(const Sales_data&);
	string bookNo;
	unsigned units_sold = 0;
	double revenue = 0.0;
    
};
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold+=rhs.units_sold;
    revenue+=rhs.revenue;
    return *this;
}
int main(int argc,char *argv[])
{
    Sales_data total;
    double totalprice;
    if(cin>>total.bookNo>>total.units_sold>>totalprice)
    {
        total.revenue=total.units_sold*totalprice;
        Sales_data trans;
        double transprice;
        while(cin>>trans.bookNo>>trans.units_sold>>transprice)
        {
            trans.revenue=trans.units_sold*transprice;
            if(total.isbn()==trans.isbn())
            {
                total.combine(trans);
            }
            else
            {
                cout<

7.4

#pragma once
#include
#include
using namespace std;
class Person
{
private:
	string name;
	string address;
};

7.5

#pragma once
#include
#include
using namespace std;
class Person
{
private:
	string name;
	string address;
public:
	string returnName()const{ return name ;}
	string retrunAddress()const{ return address; }
};

7.5

Sales_data.h

#pragma once
#include
#include
using namespace std;
class Sales_data
{
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double  avg_price() const;
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;

};
double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs)
{
    Sales_data sum = lhs;
    sum.combine(rhs);
    return sum;
}
istream& read(istream& is, Sales_data& item)
{
    double price = 0.0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
ostream& print(ostream& os, Sales_data& item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " "<

7.7

Sales_data.cpp


#include 
#include "Sales_data.h"

int main()
{
    Sales_data total;
    double totalprice=0.0;
    if (read(cin,total))
    {
        total.revenue = total.units_sold * totalprice;
        Sales_data trans;
        double transprice=0.0;
        while (read(cin,trans))
        {
            trans.revenue = trans.units_sold * transprice;
            if (total.isbn() == trans.isbn())
            {
                total.combine(trans);
            }
            else
            {
                print(cout,total);
                if (total.units_sold != 0)
                {
                    cout <

7.9

Person.h:

#pragma once
#include
#include
using namespace std;
class Person
{
private:
public:
	string returnName()const{ return name ;}
	string retrunAddress()const{ return address; }
	string name;
	string address;
};
istream& read(istream& is, Person& item)
{
	is >> item.name >> item.address;
	return is;
}
ostream& print(ostream& os, Person& item)
{
	os << item.name << item.address;
	return os;
}

7.11

Sales_data.h

#pragma once
#include
#include
using namespace std;
class Sales_data
{
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double  avg_price() const;
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
    Sales_data() = default;
    Sales_data(const string& s) :bookNo(s) {};
    Sales_data(istream&);
    Sales_data(const string& s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p* n) {}
};

double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs)
{
    Sales_data sum = lhs;
    sum.combine(rhs);
    return sum;
}
istream& read(istream& is, Sales_data& item)
{
    double price = 0.0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
Sales_data::Sales_data(istream& is)
{
    read(is, *this);
}
ostream& print(ostream& os, Sales_data& item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price();
    return os;
}

Sales_data.cpp


#include 
#include "Sales_data.h"

int main()
{
    Sales_data data1;
    print(cout, data1) << endl;
    Sales_data data2("A");
    print(cout, data2) << endl;
    Sales_data data3("B", 1, 11);
    print(cout, data3) << endl;
    Sales_data data4(cin);
    print(cout, data4) << endl;
}	

7.12

#pragma once
#include
#include
using namespace std;
class Sales_data
{
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double  avg_price() const;
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
    Sales_data() = default;
    Sales_data(const string& s) :bookNo(s) {};
    Sales_data(istream& is)
    {
        double price = 0;
        is >> this->bookNo >> this->units_sold >> price;
        this->revenue = price * this->units_sold;
    }
    Sales_data(const string& s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p* n) {}
};

double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs)
{
    Sales_data sum = lhs;
    sum.combine(rhs);
    return sum;
}
istream& read(istream& is, Sales_data& item)
{
    double price = 0.0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
//Sales_data::Sales_data(istream& is)
//{
//    read(is, *this);
//}
ostream& print(ostream& os, Sales_data& item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price();
    return os;
}

OR

#pragma once
#include
#include
using namespace std;
class Sales_data;
istream& read(istream& is, Sales_data& item);
class Sales_data
{
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double  avg_price() const;
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
    Sales_data() = default;
    Sales_data(const string& s) :bookNo(s) {};
    Sales_data(istream& is);
    Sales_data(const string& s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p* n) {}
};

double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs)
{
    Sales_data sum = lhs;
    sum.combine(rhs);
    return sum;
}
istream& read(istream& is, Sales_data& item)
{
    double price = 0.0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
Sales_data::Sales_data(istream& is)
{
    read(is, *this);
}
ostream& print(ostream& os, Sales_data& item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price();
    return os;
}

7.13

Sales_data.cpp


#include 
#include "Sales_data.h"

int main()
{
    Sales_data total(cin);
    if (!total.isbn().empty())
    {
        Sales_data trans;
        while (read(cin, trans))
        {
            if (total.isbn() == trans.isbn())
            {
                total.combine(trans);
            }
            else
            {
                print(cout, total) << endl;
                total = trans;
            }
        }
        print(cout, total) << endl;
    }
    else
    {
        cerr << "No data?!" << endl;
    }
}

7.14

Sales_data():bookNo(""),units_sold(0),revenue(0){};

7.15

#pragma once
#include
#include
using namespace std;
class Person;
istream& read(istream& is, Person& item);
class Person
{
private:
public:
	string returnName()const{ return name ;}
	string retrunAddress()const{ return address; }
	string name;
	string address;
	Person() :name(""), address("") {};
	Person(string &n, string &a):name(n),address(a) {};
	Person(istream& is) { read(is, *this); }
};
istream& read(istream& is, Person& item)
{
	is >> item.name >> item.address;
	return is;
}
ostream& print(ostream& os, Person& item)
{
	os << item.name << item.address;
	return os;
}

7.21

item_data.h : 声明友元函数后其他不变

#pragma once
#include
#include
using namespace std;
class Sales_data;
istream& read(istream& is, Sales_data& item);
class Sales_data
{
    friend Sales_data add(const Sales_data& lhs, const Sales_data& rhs);
    friend istream & read(istream& is, Sales_data& item);
    friend ostream& print(ostream& os, Sales_data& item);
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double  avg_price() const;
    Sales_data() = default;
    Sales_data(const string& s) :bookNo(s) {};
    Sales_data(istream& is);
    Sales_data(const string& s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p* n) {}
private:
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
};

double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs)
{
    Sales_data sum = lhs;
    sum.combine(rhs);
    return sum;
}
istream& read(istream& is, Sales_data& item)
{
    double price = 0.0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
Sales_data::Sales_data(istream& is)
{
    read(is, *this);
}
ostream& print(ostream& os, Sales_data& item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price();
    return os;
}

7.22

类内类外声明

#pragma once
#include
#include
using namespace std;
class Person;
istream& read(istream& is, Person& item);
ostream& print(ostream& os, Person& item);
class Person
{
	friend istream& read(istream& is, Person& item);
	friend ostream& print(ostream& os, Person& item);
private:
	string name;
	string address;
public:
	string returnName()const { return name; }
	string retrunAddress()const { return address; }
	Person() :name(""), address("") {};
	Person(string &n, string &a):name(n),address(a) {};
	Person(istream& is) { read(is, *this); }
};
istream& read(istream& is, Person& item)
{
	is >> item.name >> item.address;
	return is;
}
ostream& print(ostream& os, Person& item)
{
	os << item.name << item.address;
	return os;
}

7.23

#pragma once
#include
#include
using namespace std;
class Screen
{
public:
	typedef string::size_type pos;
	Screen() = default;//声明使用自定义的默认构造函数
	Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht* wd, c) {  };//自定义的默认构造函数
	char get()const { return contents[cursor]; }//隐式内联定义get
	inline char get(pos ht, pos wd)const;//显示定义内联get
	Screen& move(pos r, pos c);//外部修饰函数move
	void some_member() const;
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
	mutable size_t access_ctr;
};
inline Screen& Screen::move(pos r, pos c)
{
	pos row = r * width;
	cursor = row + c;
	return *this;
}
char Screen::get(pos r, pos c)const
{
	pos row = r * width;
	return contents[row + c];
}
void Screen::some_member() const
{
	++access_ctr;
}

7.24

#pragma once
#include
#include
using namespace std;
class Screen
{
public:
	typedef string::size_type pos;
	Screen() {};//声明使用自定义的默认构造函数
	Screen(pos ht, pos wd) :height(ht), width(wd) {};
	Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht* wd, c) {};//自定义的默认构造函数
	char get()const { return contents[cursor]; }//隐式内联定义get
	inline char get(pos ht, pos wd)const;//显示定义内联get
	Screen& move(pos r, pos c);//外部修饰函数move
	void some_member() const;
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
	mutable size_t access_ctr;
};
inline Screen& Screen::move(pos r, pos c)
{
	pos row = r * width;
	cursor = row + c;
	return *this;
}
char Screen::get(pos r, pos c)const
{
	pos row = r * width;
	return contents[row + c];
}
void Screen::some_member() const
{
	++access_ctr;
}

7.26

inline double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}

7.27

#XXXXXXXXXXXXXXXXXXXXXXXX
#XXXXXXXXXXXXXXXXXXXXXXXX

Screen.h

#pragma once
#include
#include
using namespace std;
class Screen
{
public:
	typedef string::size_type pos;
	Screen() {};//声明使用自定义的默认构造函数
	Screen(pos ht, pos wd) :height(ht), width(wd) {};
	Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht* wd, c) {};//自定义的默认构造函数
	char get()const { return contents[cursor]; }//隐式内联定义get
	inline char get(pos ht, pos wd)const;//显示定义内联get
	Screen& move(pos r, pos c);//外部修饰函数move
	//void some_member() const;
	Screen& set(char);
	Screen& set(pos, pos, char);
	Screen& display(ostream& os) { do_display(os); return *this; }
	const Screen& display(ostream& os)const { do_display(os); return *this; }
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
	mutable size_t access_ctr;
	void do_display(ostream& os) const { os << contents; }
};
inline Screen& Screen::move(pos r, pos c)
{
	contents[cursor] = c;
	return *this;
}
inline Screen& Screen::set(char c)
{
	contents[cursor] = c;
	return *this;
}
inline Screen& Screen::set(pos r, pos col, char ch)
{
	contents[r * width + col] = ch;
	return* this;
}

Screen.cpp:

#include "Screen.h"	
#include
#include
using namespace std;
int main()
{
	Screen myScreen{ 5,5,'X' };
	myScreen.move(4, 0).set('#').display(cout);
	cout << "\n";
	myScreen.display(cout);
	cout << "\n";
}

7.29

#XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX

7.31

#pragma once
class Y;
class X
{
	Y* point;
};
class Y
{
	X element;
};

7.32

#pragma once
#include
#include
#include
using namespace std;
class Screen;
//首先声明Window_mgr类
class Window_mgr
{
public:
	using ScreenIndex = vector::size_type;
	void clear(ScreenIndex);//声明clear函数,但不定义它
private:
	vector screens;
};
class Screen
{
public:
	friend void Window_mgr::clear(ScreenIndex);//定义Screen,对clear的友元声明
	typedef string::size_type pos;
	Screen() {};//声明使用自定义的默认构造函数
	Screen(pos ht, pos wd) :height(ht), width(wd) {};
	Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht* wd, c) {};//自定义的默认构造函数
	char get()const { return contents[cursor]; }//隐式内联定义get
	inline char get(pos ht, pos wd)const;//显示定义内联get
	Screen& move(pos r, pos c);//外部修饰函数move
	//void some_member() const;
	Screen& set(char);
	Screen& set(pos, pos, char);
	Screen& display(ostream& os) { do_display(os); return *this; }
	const Screen& display(ostream& os)const { do_display(os); return *this; }
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
	mutable size_t access_ctr;
	void do_display(ostream& os) const { os << contents; }
};
inline Screen& Screen::move(pos r, pos c)
{
	contents[cursor] = c;
	return *this;
}
inline Screen& Screen::set(char c)
{
	contents[cursor] = c;
	return *this;
}
inline Screen& Screen::set(pos r, pos col, char ch)
{
	contents[r * width + col] = ch;
	return* this;
}
//定义clear
void Window_mgr::clear(ScreenIndex i)
{
	Screen& s = screens[i];
	s.contents = string(s.height * s.width, ' ');
}

7.33

类内声明已省略

Screen::pos Screen::size()const
{
	return height * width;
}

7.41

result:

constructor 1
constructor 2
AAA 11 2
constructor 1
constructor 2
constructor 1
constructor 3

Sales_data.h

#pragma once
#include
#include
using namespace std;
class Sales_data;
istream& read(istream& is, Sales_data& item);
class Sales_data
{
    friend Sales_data add(const Sales_data& lhs, const Sales_data& rhs);
    friend istream & read(istream& is, Sales_data& item);
    friend ostream& print(ostream& os, Sales_data& item);
public:
    string isbn()const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double  avg_price() const;
    Sales_data(const string& s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p* n) { cout << "constructor 1" << endl; }
    Sales_data() :Sales_data("", 0, 0) { cout << "constructor 2" << endl; }
    Sales_data(string& s) :Sales_data(s, 0, 0) { cout << "constructor 3" << endl; }
    Sales_data(istream& is) :Sales_data() { read(is, *this); }
    
private:
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
};

inline double Sales_data::avg_price()const
{
    if (units_sold) return revenue / units_sold;
    else return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs)
{
    Sales_data sum = lhs;
    sum.combine(rhs);
    return sum;
}
istream& read(istream& is, Sales_data& item)
{
    double price = 0.0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
//Sales_data::Sales_data(istream& is)
//{
//    read(is, *this);
//}
ostream& print(ostream& os, Sales_data& item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price();
    return os;
}

Sales_data.cpp:


#include 
#include "Sales_data.h"

int main()
{
    Sales_data total(cin);
    if (!total.isbn().empty())
    {
        string str = "ss";
        Sales_data trans;
        Sales_data trans2(str);
        while (read(cin, trans))
        {
            if (total.isbn() == trans.isbn())
            {
                total.combine(trans);
            }
            else
            {
                print(cout, total) << endl;
                total = trans;
            }
        }
        print(cout, total) << endl;
    }
    else
    {
        cerr << "No data?!" << endl;
    }
}

7.43

#pragma once
class NoDefault
{
public:
	NoDefault(int n) {};
};
class C
{
	C() :num(0) {};
private:
	NoDefault num;
};

7.50

选择单个参数的构造函数:

	explicit Person(istream& is) { read(is, *this); }

7.53

#pragma once
class Debug
{
public:
	constexpr Debug(bool b=true):hw(b),io(b),other(b){}
	constexpr Debug(bool h,bool i,bool o):hw(h),io(i),other(o){}
	constexpr bool any() { return hw || io || other; }
	void set_io(bool b) { io = b; }
	void set_hw(bool b) { hw = b; }
	void set_other(bool b) { hw = b; }
private:
	bool hw;
	bool io;
	bool other;
};

7.55

#include
#include
#include

using namespace std;
struct Data {
	int ival;
	string s;
};
int main()
{
	cout << boolalpha;
	cout << is_literal_type::value << endl;
}

7.57

#pragma once
#include
#include
using namespace std;
class Account
{
public:
	void calculate() { amount += amount * interestRate; }
	static double rate() { return interestRate; }
	static void rate(double);
private:
	string owner;
	double amount;
	static double interestRate;
	static double initRate();
};

9. 顺序容器

9.1

list>;

9.4

#include
#include
using namespace std;
bool checkVector(vector::const_iterator begin, vector::const_iterator end, int val);
int main()
{
	vector ivec;
	int num;
	cout << "enter the number until you put in the -1:" << endl;
	while (cin >> num)
	{
		if (num == -1) break;
		ivec.push_back(num);
	}
	cout << "enter the number which do you wanna check:" << endl;
	int num2;
	cin >> num2;
	cout << boolalpha << checkVector(ivec.begin(), ivec.end(), num2);
	return 0;
}
bool checkVector(vector::const_iterator begin,vector::const_iterator end, int val)
{
	while (begin != end)
	{
		if (*begin == val)  return true;
	}
	return false;
}

9.5

#include
#include
using namespace std;
vector::const_iterator& returnVector(vector::const_iterator begin, vector::const_iterator end, int val);
int main()
{
	vector ivec;
	int num;
	cout << "enter the number until you put in the -1:" << endl;
	while (cin >> num)
	{
		if (num == -1) break;
		ivec.push_back(num);
	}
	cout << "enter the number which do you wanna check:" << endl;
	int num2;
	cin >> num2;
	returnVector(ivec.begin(), ivec.end(), num2);
	return 0;
}
vector::const_iterator& returnVector(vector::const_iterator begin,vector::const_iterator end, int val)
{
	while (begin != end)
	{
		if (*begin == val)  return begin; break;
	}
	cout << "no element" << endl;
	return begin;
}

9.11

#include
#include
using namespace std;
void coutElement(vector::const_iterator begin, vector::const_iterator end);
int main()
{
	vector vec1;
	vector vec2(vec1);
	vector vec3 = vec2;
	vector vec4(10);
	vector vec5 = { 1,2,3,4,5,6 };
	vector vec6(vec5.begin(), vec5.end() - 1);
	coutElement(vec1.begin(),vec1.end());
	coutElement(vec2.begin(), vec2.end());
	coutElement(vec3.begin(), vec3.end());
	coutElement(vec4.begin(), vec4.end());
	coutElement(vec5.begin(), vec5.end());
	coutElement(vec6.begin(), vec6.end());
}
void coutElement(vector::const_iterator begin,vector::const_iterator end)
{
	while (begin != end)
	{
		cout << *begin << " ";
		begin++;
	}
	cout << endl;
}

9.13

#include
#include
#include
using namespace std;

int main()
{
	list lst{ 1,2,3,4,5 };
	vector vec(lst.begin(), lst.end());
	for (auto ele : vec)
	{
		cout << ele << " ";
	}
	cout << endl;
	vector vec2{ 1,2,3,4,5,6, };
	vector vec3(vec2.begin(), vec2.end());
	for (auto ele : vec3)
	{
		cout << ele << " ";
	}
}

9.14

#include
#include
#include
#include

using namespace std;
int main()
{
	list lst {"abcde"};
	vector vec;
	vec.assign(lst.begin(), lst.end());
	for (auto ele : vec)
	{
		cout << ele << endl;;
	}
}

9.15

#include
#include
#include
#include

using namespace std;
int main()
{
	vector vec1;
	vector vec2;
	cout << "enter the vec1:" << endl;
	int num;
	while (cin >> num)
	{
		if (num == -1) break;
		vec1.push_back(num);
	}
	cout << "enter the vec2:" << endl;
	int Num;
	while (cin >> Num)
	{
		if (Num == -1)break;
		vec2.push_back(Num);
	}
	if (vec1 == vec2) cout << "vec1==vec2" << endl;
	else if (vec1 > vec2) cout << "vec1>vec2" << endl;
	else  cout << "vec1

9.16

#include
#include
#include
#include

using namespace std;
int main()
{
	vector vec1;
	list lst;
	cout << "enter the vec1:" << endl;
	int num;
	while (cin >> num)
	{
		if (num == -1) break;
		vec1.push_back(num);
	}
	cout << "enter the list:" << endl;
	int Num;
	while (cin >> Num)
	{
		if (Num == -1)break;
		lst.push_back(Num);
	}
	vector vec2;
	vec2.assign(lst.begin(), lst.end());
	if (vec1 == vec2) cout << "vec1==list" << endl;
	else if (vec1 > vec2) cout << "vec1>list" << endl;
	else  cout << "vec1

9.18

#include
#include
#include
using namespace std;

int main()
{
	cout << "please input some string:" << endl;
	string str;
	deque deq;
	while (cin >> str)
	{
		if (str == "quit") break;
		deq.push_back(str);
	}
	auto iter = deq.begin();
	while( iter!= deq.end())
	{
		cout << *iter<< " ";
		iter++;
	}
}

9.19

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

int main()
{
	cout << "please input some string:" << endl;
	string str;
	list lst;
	while (cin >> str)
	{
		if (str == "quit") break;
		lst.push_back(str);
	}
	auto iter = lst.begin();
	while( iter!= lst.end())
	{
		cout << *iter<< " ";
		iter++;
	}
}

9.20

#include
#include
#include
using namespace std;

int main()
{
	cout << "enter some numbers while the number != 0:" << endl;
	int num;
	list numList;
	while (cin >> num)
	{
		if (num == 0) break;
		numList.insert(numList.begin(), num);
	}
	deque evenDeque;
	deque oddDeque;
	for (auto iter = numList.begin(); iter != numList.end(); iter++)
	{
		if (*iter % 2 == 0) evenDeque.push_back(*iter);
		else oddDeque.push_back(*iter);
	}
	for (auto ele : evenDeque)
	{
		cout << ele << " ";
	}
	cout << endl;
	for (auto ele : oddDeque)
	{
		cout << ele << " ";
	}
}

9.24

#include
#include
using namespace std;

int main()
{
	vectorvec;
	cout << "at: " << vec.at(1) << endl;
	cout << "[1]: " << vec[1] << endl;
	cout << "front: " << vec.front() << endl;
	cout << "begin: " << *vec.begin() << endl;

}

9.26

#include
#include
#include
using namespace std;

int main()
{
	vector vec;
	list lst;
	int ia[] = { 0,1,1,2,3,5,8,13,21,55,89 };
	for (auto &elem : ia)
	{
		vec.push_back(elem);
		lst.push_back(elem);
	}
	auto iter1 = vec.begin();
	while(iter1!=vec.end())
	{
		if (*iter1 % 2 == 0)
			iter1 = vec.erase(iter1);
		else
			iter1++;
	}
	for (auto iter2 = lst.begin(); iter2 != lst.end(); )
	{
		if (*iter2 % 2 != 0)
			iter2 = lst.erase(iter2);
		else
			iter2++;
	}
	cout << "vec:" << endl;
	for (auto& elem2 : vec)
	{
		cout << elem2 << " ";
	}
	cout << endl;
	cout << "lst: " << endl;
	for (auto& elem2 : lst)
	{
		cout << elem2 << " ";
	}
}

9.27

#include
#include
using namespace std;

int main()
{
	cout << "please input some numbers until you enter the 0: " << endl;
	int num;
	forward_list flist{ 1,2,3,4,6 };
	auto prev = flist.before_begin();
	auto curr = flist.begin();
	while (curr != flist.end())
	{
		if (!(*curr % 2))
			curr = flist.erase_after(prev);
		else {
			prev = curr;
			curr++;
		}
	}
	for (auto elem : flist)
	{
		cout << elem << " ";
	}

}

9.28

#include
#include
using namespace std;
void insertString(forward_list &flst, const string& targetsstr, const string& str);
int main()
{
	forward_list flst= { "a","b","c","d" };
	cout << "enter the string which do you wanna find:" << endl;
	string str1;
	cin >> str1;
	cout << "enter the string which do you wannna add: " << endl;
	string str2;
	cin >> str2;
	insertString(flst, str1, str2);
	for (auto elem : flst)
	{
		cout << elem << " ";
	}

}
void insertString(forward_list &flst, const string& targetsstr, const string& str)
{
	auto prev = flst.before_begin();
	auto curr = flst.begin();
	while (curr != flst.end())
	{
		if (*curr == targetsstr)
		{
			flst.insert_after(curr, str);
			return;
		}
		else
		{
			prev = curr;
			++curr;
		}
	}
	flst.insert_after(prev,targetsstr);
}

9.31

#include
#include

using namespace std;
int main()
{
	list li = { 1,2,3,4,5,6,7,8,9, };
	auto iter = li.begin();
	while (iter != li.end())
	{
		if (*iter % 2)
		{
			iter = li.insert(iter, *iter);
			iter ++;
			iter ++;
		}
		else
		{
			iter = li.erase(iter);
		}
	}
	for(const auto i:li)
	{
		cout << i << " ";
	}
}
#include
#include

using namespace std;
int main()
{
	forward_list li = { 1,2,3,4,5,6,7,8,9, };
	auto iter = li.begin();
	auto prev = li.before_begin();
	while (iter != li.end())
	{
		if (*iter % 2)
		{
			iter = li.insert_after(iter, *iter);
			prev = iter;
			iter ++;
		}
		else
		{
			iter = li.erase_after(prev);
		}
	}
	for(const auto i:li)
	{
		cout << i << " ";
	}
}

9.40

#include
#include

using namespace std;
int main()
{
	vector ivec;
	cout << "size:" << ivec.size();
	cout << "capacity:" << ivec.capacity() << endl;
	for (vector::size_type ix = 0; ix != 24; ++ix)
	{
		ivec.push_back(ix);
	}
	cout << "size:" << ivec.size();
	cout << "capacity:" << ivec.capacity() << endl;
	ivec.reserve(50);
	cout << "size:" << ivec.size();
	cout << "capacity:" << ivec.capacity() << endl;
}
size:0capacity:0
size:24capacity:28
size:24capacity:50

9.41

#include
#include
#include

using namespace std;
int main()
{
	vector ch = { 'C','+','+' };
	string str(ch.begin(), ch.end());
	for (auto i : str)
	{
		cout << i;
	}
}

9.43

//it can't compile it on gcc.
#include 
#include 

using namespace std;

void replace_with_str(string &s, const string &oldVal, const string &newVal)
{
	auto iter = s.begin();

	while (iter != s.end())
	{
		if (s.end()-iter

9.44


#include 
#include 

using namespace std;

void replace_with_str(string &s, const string &oldVal, const string &newVal)
{
	string::size_type index = 0;

	while (index!=s.size())
	{
		if (oldVal == string(s,index,oldVal.size()))
		{
			s.replace(index, oldVal.size(), newVal);
		}
			++index;
	}
}

int main()
{
	string s("tho thru ");

	replace_with_str(s, "tho", "thought");
	cout << s << endl;

	replace_with_str(s, "thru", "through");
	cout << s << endl;

	return 0;
}

9.45

#include 
#include 

using namespace std;

void replace_with_str(string& s, const string& oldVal, const string& newVal)
{
	string::size_type index = 0;

	while (index != s.size())
	{
		if (oldVal == string(s,index,oldVal.size()))
		{
			s.replace(index, oldVal.size(), newVal);
		}
			++index;
	}
}

int main()
{
	string s("tho thru");

	replace_with_str(s, "tho", "though");
	cout << s << endl;

	replace_with_str(s, "thru", "through");
	cout << s << endl;

	return 0;
}

9.46

#include 
#include 

using namespace std;
string addPreEnd(const string& name, const string& pre, const string& end);

int main()
{
	string name,str;
	cin >> name;
	str = addPreEnd(name, "Mr.", "Jr.");
	cout << str;
}
string addPreEnd(const string& name, const string& pre, const string& end)
{
	string str = name;
	str.insert(str.begin(), pre.cbegin(), pre.cend());
	return str.append(end);
}

9.47

#include 
#include 

using namespace std;
string addPreEnd(const string& name, const string& pre, const string& end);

int main()
{
	string name,str;
	cin >> name;
	str = addPreEnd(name, "Mr.", "Jr.");
	cout << str;
}
string addPreEnd(const string& name, const string& pre, const string& end)
{
	string str = name;
	str.insert(0,pre);
	return str.insert(str.size(),end);
}

9.48

#include 
#include 

using namespace std;
int main()
{
	string numbers{ "123456789" };
	string alphabet{ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
	string str = "ab2c3d7R4E6";
	string::size_type pos2 = 0;
	string::size_type pos = 0;
	while ((pos = str.find_first_of(numbers, pos)) != string::npos)
	{	
		cout << str[pos] <<" ";
		++pos;
	}
	while ((pos2 = str.find_first_not_of(numbers, pos2)) != string::npos)
	{
		cout << str[pos2] << " ";
		++pos2;
	}
}

9.49

#include 
#include 
#include

using namespace std;
int main()
{
	vector vec(10, "5");
	int sum = 0;
	for(string s:vec)
	{
		sum += stoi(s);
	}
	cout << sum << endl;

	vector vec2(10, "5.5");
	double dsum = 0;
	for (string s : vec2)
	{
		dsum += stod(s);
	}
	cout << dsum << endl;
}

9.50

#include 
#include 

using namespace std;

class my_date
{
public:
	my_date(const string&);
private:
	unsigned int year;
	unsigned int month;
	unsigned int day;
};

my_date::my_date(const string& s)
{
	string date_str = s;
	string::size_type index1 = 0;
	string::size_type index2 = 0;

	if (s.find(',') != string::npos)//January 1, 1900
	{
		index1 = s.find(' ');
		index2 = s.find(',', index1 + 1);
		cout << "year: " << s.substr(index2 + 1, s.size()) << "; month: " << s.substr(0, index1) << "; day: " << s.substr(index1 + 1, index2 - index1 - 1) << endl;
		// month = stoi(s.substr(0, index1));
		if (s.find("Jan") < s.size())  month = 1;
		if (s.find("Feb") < s.size())  month = 2;
		if (s.find("Mar") < s.size())  month = 3;
		if (s.find("Apr") < s.size())  month = 4;
		if (s.find("May") < s.size())  month = 5;
		if (s.find("Jun") < s.size())  month = 6;
		if (s.find("Jul") < s.size())  month = 7;
		if (s.find("Aug") < s.size())  month = 8;
		if (s.find("Sep") < s.size())  month = 9;
		if (s.find("Oct") < s.size())  month = 10;
		if (s.find("Nov") < s.size())  month = 11;
		if (s.find("Dec") < s.size())  month = 12;
		day = stoi(s.substr(index1 + 1, index2 - index1 - 1));
		year = stoi(s.substr(index2 + 1, s.size()));
	}
	else if (s.find('/') != string::npos)//1/1/1900
	{
		index1 = s.find('/');
		index2 = s.find('/', index1 + 1);
		cout << "year: " << s.substr(index2 + 1, s.size()) << "; month: " << s.substr(0, index1) << "; day: " << s.substr(index1 + 1, index2 - index1 - 1) << endl;
		month = stoi(s.substr(0, index1));
		day = stoi(s.substr(index1 + 1, index2 - index1 - 1));
		year = stoi(s.substr(index2 + 1, s.size()));
	}
	else//Jan 1 1900
	{
		index1 = s.find(' ');
		index2 = s.find(' ', index1 + 1);
		cout << "year: " << s.substr(index2 + 1, s.size()) << "; month: " << s.substr(0, index1) << "; day: " << s.substr(index1 + 1, index2 - index1 - 1) << endl;
		// month = stoi(s.substr(0, index1));
		if (s.find("Jan") < s.size())  month = 1;
		if (s.find("Feb") < s.size())  month = 2;
		if (s.find("Mar") < s.size())  month = 3;
		if (s.find("Apr") < s.size())  month = 4;
		if (s.find("May") < s.size())  month = 5;
		if (s.find("Jun") < s.size())  month = 6;
		if (s.find("Jul") < s.size())  month = 7;
		if (s.find("Aug") < s.size())  month = 8;
		if (s.find("Sep") < s.size())  month = 9;
		if (s.find("Oct") < s.size())  month = 10;
		if (s.find("Nov") < s.size())  month = 11;
		if (s.find("Dec") < s.size())  month = 12;
		day = stoi(s.substr(index1 + 1, index2 - index1 - 1));
		year = stoi(s.substr(index2 + 1, s.size()));
	}
	cout << "year: " << year << "; month: " << month << "; day: " << day << endl;
}

int main()
{
	my_date my_date1("January 1, 1900");
	my_date my_date2("1/1/1900");
	my_date my_date3("Jan 1 1900");

	return 0;
}

9.51

#include 
#include 
#include 

using std::string; using std::cout; using std::endl; using std::stack;

int main()
{
    string expression{ "This is (pezy)." };
    bool bSeen = false;
    stack stk;
    for (const auto &s : expression)
    {
        if (s == '(') { bSeen = true; continue; }
        else if (s == ')') bSeen = false;
        
        if (bSeen) stk.push(s);
    }
    
    string repstr;
    while (!stk.empty())
    {
        repstr += stk.top();
        stk.pop();
    }
    
    expression.replace(expression.find("(")+1, repstr.size(), repstr);
    
    cout << expression << endl;
    
    return 0;
}

10.泛型算法

10.1

#include
#include
#include

using namespace std;
int main()
{
	vector vec = { 1,2,3,4,5,6,5 };
	int n = count(vec.cbegin(), vec.cend(), 5);
	cout << "count=" <

10.2

#include
#include
#include
#include

using namespace std;
int main()
{
	list list = { "aaa","bbb","ccc","aaa" };
	int n = count(list.cbegin(), list.cend(), "aaa");
	cout << "count=" <

10.3

#include
#include
#include
#include

using namespace std;
int main()
{
	vector vec = { 1,2,3,4,5 };
	int sum = accumulate(vec.cbegin(), vec.cend(), 0);
	cout << sum << endl;
}

10.6

#include
#include
#include
#include

using namespace std;
int main()
{
	vector vec = { 1,2,3,4,5 };
	fill_n(vec.begin(), vec.size(), 0);
	for (const auto i:vec)
	{
		cout << i << " ";
	}
}

10.9

#include
#include
#include
#include
#include

using namespace std;
void elimDups(vector& words);
int main()
{
	vector vec = { "the", "fox", "over", "quick", "red", "the", "red", "turtle" };
	for (auto i : vec)
	{
		cout << i << " ";
	}
	cout << endl;
	elimDups(vec);
}

void elimDups(vector& words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
	for (auto i : words)
	{
		cout << i << " ";
	}
}

10.11

#include
#include
#include
#include
#include

using namespace std;
void elimDups(vector& words);
bool isShorter(const string& s1, const string& s2);
int main()
{
	vector vec = { "the", "fox", "over", "quick", "red", "the", "red", "turtle" };
	for (auto i : vec)
	{
		cout << i << " ";
	}
	cout << endl;
	elimDups(vec);
	//isShorter作为谓词传递
	stable_sort(vec.begin(), vec.end(), isShorter);
	for (auto i : vec)
	{
		cout << i << " ";
	}
}

void elimDups(vector& words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
	for (auto i : words)
	{
		cout << i << " ";
	}
	cout << endl;
}

bool isShorter(const string& s1, const string& s2)
{
	return s1.size() < s2.size();
}

10.12

#include      // std::cout
#include     // std::stable_sort
#include        // std::vector

using namespace std;



class Sales_data {
public:
    string isbn()const { return bookNo; }
    Sales_data(string str);
private:
    string bookNo;
};

bool compareIsbn(const Sales_data& sales_data1, const Sales_data& sales_data2);

Sales_data::Sales_data(string str)
{
    this->bookNo = str;
}

bool compareIsbn(const Sales_data& sales_data1, const Sales_data& sales_data2)
{
    return (sales_data1.isbn() < sales_data2.isbn());
}
int main()
{
    string str1 = "abc";
    string str2 = "def";
    Sales_data data1(str1);
    Sales_data data2(str2);
    vector vec{data1,data2};
//    vector vec2;
    vec.push_back(data2);
    vec.push_back(data1);

    sort(vec.begin(), vec.end(), compareIsbn);
    int i;
    for (i = 0; i < vec.size(); i++)
    {
        cout << vec[i].isbn() << " ";
    }
    return 0;
}

10.13

#include
#include
#include
#include
#include

using namespace std;
bool greaterThanfive(const string& s);

int main()
{
	vector vec = { "aa","bb","cc","abcdef","ghijk" };
	//返回迭代器,指向true元素后的位置
	auto iter = partition(vec.begin(), vec.end(), greaterThanfive);
	for (const auto i : vec)
	{
		cout << i << " ";
	}
	cout << endl;

	vec.erase(iter, vec.end());
	for (const auto s : vec)
	{
		cout << s << " ";
	}
	cout << endl;
	return 0;
}

bool greaterThanfive(const string& s)
{
	return s.size() >= 5;
}

10.14

#include

using namespace std;

int main()
{
	int m, n;
	cout << "please input two numbers:" << endl;
	cin >> m >> n;
	auto sum = [] (int m,int n){return m + n; };
	cout << sum(m, n) << endl;
}

10.15

#include

using namespace std;

int main()
{
	int m, n;
	cout << "please input two numbers:" << endl;
	cin >> m >> n;
	auto sum = [m] (int n){return m + n; };
	cout << sum(n) << endl;	
}

10.16

#include
#include
#include
#include
#include
#include "C++peimier.h"

using namespace std;

void elimDups(vector& words);
string make_plural(rsize_t ctr, const string& word, const string& ending);
void biggies(vector& words, vector::size_type sz);

int main()
{
	vector vec;
	cout << "please input string:" << endl;
	string str;
	while (true)
	{
		cin >> str;
		if (str == "over")
			break;
		vec.push_back(str);
	}
	cout << "please input a number to evaluate:" << endl;
	vector::size_type n;
	cin >> n;
	biggies(vec, n);
}

void elimDups(vector& words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
	for (auto i : words)
	{
		cout << i << " ";
	}
	cout << endl;
}

string make_plural(rsize_t ctr, const string& word, const string& ending)
{
	return(ctr > 1) ? word + ending : word;
}

void biggies(vector& words, vector::size_type sz)
{
	elimDups(words);
	stable_sort(words.begin(), words.end(), [sz](const string& a, const string& b) {return a.size() < b.size(); });
	auto wc = find_if(words.begin(), words.end(), [sz](const string& a) {return a.size() >= sz; });
	auto count = words.end() - wc;
	cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer " << endl;
	for_each(wc, words.end(), [](const string& s) {cout << s << " "; });
	cout << endl;
}

10.17

#include      // std::cout
#include     // std::stable_sort
#include        // std::vector

using namespace std;



class Sales_data {
public:
    string isbn()const { return bookNo; }
    Sales_data(string str);
private:
    string bookNo;
};

bool compareIsbn(const Sales_data& sales_data1, const Sales_data& sales_data2);

Sales_data::Sales_data(string str)
{
    this->bookNo = str;
}

bool compareIsbn(const Sales_data& sales_data1, const Sales_data& sales_data2)
{
    return (sales_data1.isbn() < sales_data2.isbn());
}
int main()
{
    string str1 = "abc";
    string str2 = "def";
    Sales_data data1(str1);
    Sales_data data2(str2);
    vector vec;
    //    vector vec2;
    vec.push_back(data2);
    vec.push_back(data1);

    stable_sort(vec.begin(), vec.end(), [](const Sales_data& sales_data1, const Sales_data& sales_data2) {return sales_data1.isbn() < sales_data2.isbn(); });

    for (auto i:vec)
    {
        cout << i.isbn() << " ";
    }
    return 0;
}

10.18

#include
#include
#include
#include
#include
#include "C++peimier.h"

using namespace std;

void elimDups(vector& words);
string make_plural(rsize_t ctr, const string& word, const string& ending);
void biggies(vector& words, vector::size_type sz);

int main()
{
	vector vec;
	cout << "please input string:" << endl;
	string str;
	while (true)
	{
		cin >> str;
		if (str == "over")
			break;
		vec.push_back(str);
	}
	cout << "please input a number to evaluate:" << endl;
	vector::size_type n;
	cin >> n;
	biggies(vec, n);
}

void elimDups(vector& words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
	for (auto i : words)
	{
		cout << i << " ";
	}
	cout << endl;
}

string make_plural(rsize_t ctr, const string& word, const string& ending)
{
	return(ctr > 1) ? word + ending : word;
}

void biggies(vector& words, vector::size_type sz)
{
	elimDups(words);
	stable_sort(words.begin(), words.end(), [sz](const string& a, const string& b) {return a.size() < b.size(); });
	auto wc = partition(words.begin(), words.end(), [sz](const string& a) {return a.size() >= sz; });
	auto count = wc-words.begin();
	cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer " << endl;
	for_each(words.begin(), wc, [](const string& s) {cout << s << " "; });
	cout << endl;
}

10.19

#include
#include
#include
#include
#include
#include "C++peimier.h"

using namespace std;

void elimDups(vector& words);
string make_plural(rsize_t ctr, const string& word, const string& ending);
void biggies(vector& words, vector::size_type sz);

int main()
{
	vector vec;
	cout << "please input string:" << endl;
	string str;
	while (true)
	{
		cin >> str;
		if (str == "over")
			break;
		vec.push_back(str);
	}
	cout << "please input a number to evaluate:" << endl;
	vector::size_type n;
	cin >> n;
	biggies(vec, n);
}

void elimDups(vector& words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
	for (auto i : words)
	{
		cout << i << " ";
	}
	cout << endl;
}

string make_plural(rsize_t ctr, const string& word, const string& ending)
{
	return(ctr > 1) ? word + ending : word;
}

void biggies(vector& words, vector::size_type sz)
{
	elimDups(words);
	stable_sort(words.begin(), words.end(), [sz](const string& a, const string& b) {return a.size() < b.size(); });
	auto wc = stable_partition(words.begin(), words.end(), [sz](const string& a) {return a.size() >= sz; });
	auto count = wc-words.begin();
	cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer " << endl;
	for_each(words.begin(), wc, [](const string& s) {cout << s << " "; });
	cout << endl;
}

你可能感兴趣的:(c++)