天天看點

C++Primer練習答案-第三章

練習答案

Exercise 3.1: Rewrite the exercises from § 1.4.1 (p. 13) and § 2.6.2 (p. 76) with appropriate using declarations.

Exercise 3.2: Write a program to read the standard input a line at a time. Modify your program to read a word at a time.

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1,str2;
	getline(cin,str1);
	cout<<str1<<endl;
	cin>>str2;
	cout<<str2<<endl;
	return 0;
}
                

Exercise 3.3: Explain how whitespace characters are handled in the string input operator and in the getline function.

輸入運算符忽略空格,getline 會讀入空格。

Exercise 3.4: Write a program to read two strings and report whether the strings are equal. If not, report which of the two is larger. Now, change the program to report whether the strings have the same length, and if not, report which is longer.

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1,str2;
	cin>>str1>>str2;
	//比較是否相等,輸出較大的字元串 
	if(str1>str2)
		cout<<str1<<endl;
	else if(str1<str2)
	    cout<<str2<<endl;
	else cout<<"these two strings are equal\n";
	//比較長度,輸出長度較長的字元串
		if(str1.size()>str2.size())
		cout<<str1<<endl;
	else if(str1.size()<str2.size())
	    cout<<str2<<endl;
	else cout<<"these two strings are of the same length\n";
	return 0;
}
                

Exercise 3.5: Write a program to read strings from the standard input, concatenating what is read into one large string. Print the concatenated string. Next, change the program to separate adjacent input strings by a space.

//直接連接配接
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str,str1;
	while(cin>>str1){
		str+=str1;
	}
	cout<<str;
	return 0;
}
                
//字元之間加空格
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str,str1;
	while(cin>>str1){
		str+=(str1+" ");
	}
	cout<<str;
	return 0;
}
                

Exercise 3.6: Use a range for to change all the characters in a string to X.

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("abcdefghijk");
	cout<<str<<endl;
	for(auto &s:str)
	   s='X';
	cout<<str<<endl;
	return 0;
}
                

Exercise 3.7: What would happen if you define the loop control variable in the previous exercise as type char? Predict the results and then change your program to use a char to see if you were right.

字元串不會被改變

Exercise 3.8: Rewrite the program in the first exercise, first using a while and again using a traditional for loop. Which of the three approaches do you prefer and why?

while循環

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("abcdefghijk");
	cout<<str<<endl;
	int i=0;
	while(str[i])
	    str[i++]='X';
	cout<<str<<endl;
	return 0;
}
                

for循環

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("abcdefghijk");
	cout<<str<<endl;
    for(int i=0;str[i];++i)
	    str[i]='X';
	cout<<str<<endl;
	return 0;
}
                

Exercise 3.9: What does the following program do? Is it valid? If not, why not?

string s;

cout << s[0] << endl;

不合法,s是空字元串

Exercise 3.10: Write a program that reads a string of characters including punctuation and writes what was read but with the punctuation removed.

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1,str2;
	cin>>str1;
	for(auto s:str1)
	   if(s!=',')
	       str2+=s;
	cout<<str1<<endl<<str2<<endl;
	return 0;   
}
                

Exercise 3.11: Is the following range for legal? If so, what is the type of c?

const string s = “Keep out!”;

for (auto &c : s) { }

合法

類型是const char&

不能通過c改變字元串的值

Exercise 3.12: Which, if any, of the following vector definitions are in error? For those that are legal, explain what the definition does. For those that are not legal, explain why they are illegal.

(a) vector<vector> ivec;

合法 建立包含vector< int >的vector

(b) vector svec = ivec;

不合法,類型不一緻

(c ) vector svec(10, “null”);

合法,svec包含10個字元串 null

Exercise 3.13: How many elements are there in each of the following

vectors? What are the values of the elements?

(a) vector v1;

0個int 元素

(b) vector v2(10);

10個值為0的int

© vector v3(10, 42);

10個值為42的int

(d) vector v4{10};

一個int元素10

(e) vector v5{10, 42};

兩個int元素 10和42

(f) vector v6{10};

10個string

(g) vector v7{10, “hi”};

10個string hi

Exercise 3.14: Write a program to read a sequence of ints from cin andstore those values in a vector.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	int i;
	vector<int> ivec;
	while(cin>>i)
	   ivec.push_back(i);
	for(auto i:ivec)
	   cout<<i<<' ';
	return 0;
}
                

Exercise 3.15: Repeat the previous program but read strings this time.

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
	string  s;
	vector<string> svec;
	while(cin>>s)
	   svec.push_back(s);
	for(auto s:svec)
	   cout<<s<<' ';
	return 0;
}
                

Exercise 3.16: Write a program to print the size and contents of the vectors from exercise 3.13. Check whether your answers to that exercise were correct. If not, restudy § 3.3.1 (p. 97) until you understand why you were wrong.

Exercise 3.17: Read a sequence of words from cin and store the values a vector. After you’ve read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line.

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
	string  str;
	vector<string> svec;
	while(cin>>str)
	   svec.push_back(str);
	for(auto &s:svec)
	   for(auto &t:s)
	       t=toupper(t);
	int t=0;
	for(auto &s:svec){
		cout<<s<<'\t';
		++t;
		if(t%8==0)
		    cout<<endl;
	}
	return 0;
}
                

Exercise 3.18: Is the following program legal? If not, how might you fix it?

vector ivec;

ivec[0] = 42;

不合法,ivec為空,應改為

vector<int> ivec;
ivec.push_back(42);
                

Exercise 3.19: List three ways to define a vector and give it ten elements, each with the value 42. Indicate whether there is a preferred way to do so and why.

vector<int> v1{42,42,42,42,42,42,42,42,42,42};
vector<int> v2(10,42);
vector<int> v3;
for(int i=0;i<10;++i)
   v3.push_back(42);
vector<int> v4=v1;
                

Exercise 3.20: Read a set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so that it prints the sum of the first and last elements, followed by the sum of the second and second-to-last, and so on.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	char c='y';
	int i,j;
	vector<int> iv;
	while(c=='y'||c=='Y'){
		cout<<"input two numbers\n";
		cin>>i>>j;
		iv.push_back(i);
		iv.push_back(j);
		cout<<"y to continue input numbers,n to quit \n";
		cin>>c;
	}
	//相鄰的和
	for(decltype(iv.size()) t=0;t<iv.size();t=t+2){
		cout<<iv[t]+iv[t+1]<<' ';
		cout<<endl;
	}
	//頭尾和
	for(decltype(iv.size()) t=0;t<iv.size()/2;++t){
		cout<<iv[t]+iv[iv.size()-1-t]<<' ';
	}

	return 0;
} 
                

Exercise 3.21: Redo the first exercise from § 3.3.3 (p. 105) using iterators.

Exercise 3.22: Revise the loop that printed the first paragraph in text to instead change the elements in text that correspond to the first paragraph to all uppercase. After you’ve updated text, print its contents.

Exercise 3.23: Write a program to create a vector with ten int elements. Using an iterator, assign each element a value that is twice its current value. Test your program by printing the vector.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<int> iv={23,34,34,46,7,43,23,5,34};
	for(auto &i:iv){
	   cout<<i<<' ';
	   i*=2;
    }
    cout<<'\n';
    for(auto &i:iv)
        cout<<i<<' ';
    return 0;
	
}
                

Exercise 3.24: Redo the last exercise from § 3.3.3 (p. 105) using iterators.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	char c='y';
	int i,j;
	vector<int> iv;
	while(c=='y'||c=='Y'){
		cout<<"input two numbers\n";
		cin>>i>>j;
		iv.push_back(i);
		iv.push_back(j);
		cout<<"y to continue input numbers,n to quit \n";
		cin>>c;
	}
	//相鄰的和
	for(auto b=iv.begin();b!=iv.end();b+=2){
		cout<<*b+*(b+1)<<' ';
	}
	cout<<endl;
	//頭尾的和
	for(auto b=iv.begin();b!=iv.begin()+(iv.end()-iv.begin())/2;++b){
		cout<<*b+*(iv.end()-1-(b-iv.begin()))<<' ';
	}
	return 0;
} 

                

Exercise 3.25: Rewrite the grade clustering program from § 3.3.3 (p. 104) using iterators instead of subscripts.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<unsigned> scores(11,0);
	unsigned grade;
	auto beg=scores.begin();
	while(cin>>grade){
		if(grade<=100)
		   ++*(beg+(grade/10));
	}
	for(unsigned g:scores){
		cout<<g<<' ';
	}
	return 0;
}
                

Exercise 3.26: In the binary search program on page 112, why did we write mid = beg + (end - beg) / 2; instead of mid = (beg + end)/2;?

疊代器不能相加。

Exercise 3.27: Assuming txt_size is a function that takes no arguments

and returns an int value, which of the following definitions are illegal?

Explain why.

unsigned buf_size = 1024;

(a) int ia[buf_size];

不合法buf_size不是常量類型

(b) int ia[4 * 7 - 14];

合法

© int ia[txt_size()];

不合法txt_size傳回值是int

(d) char st[11] = “fundamental”;

不合法,長度不夠

Exercise 3.28: What are the values in the following arrays?

string sa[10];

int ia[10];

int main() {

string sa2[10];

int ia2[10];

}

ia 所有元素初始化為0

sa 10個空字元串

sa2 10個空字元串

ia2 未初始化,值未知

Exercise 3.29: List some of the drawbacks of using an array instead of a vector.

數組不如vector靈活,長度确定不可變,不支援直接指派。

Exercise 3.30: Identify the indexing errors in the following code:

constexpr size_t array_size = 10;
int ia[array_size];
for (size_t ix = 1; ix <= array_size; ++ix)
      ia[ix] = ix;
                

ia[10]超出範圍

Exercise 3.31: Write a program to define an array of ten ints. Give each

element the same value as its position in the array.

int ia[10];
for(size_t t=0;i<10;++t){
   ia[t]=t;
}
                

Exercise 3.32: Copy the array you defined in the previous exercise into another array. Rewrite your program to use vectors.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	int ia[10];
    for(size_t t=0;t<10;++t)
       ia[t]=t;
    int ia2[10];
    for(size_t t=0;t<10;++t)
        ia2[t]=ia[t];
    for(auto t:ia2)
        cout<<t<<' ';
    cout<<endl;
    vector<int> iv1,iv2;
    for(int i=0;i<10;++i)
        iv1.push_back(i);
    iv2=iv1;
    for(auto t:iv2)
        cout<<t<<' ';
    return 0;

}
                

Exercise 3.33: What would happen if we did not initialize the scores array

in the program on page 116?

數組中每個元素的值不确定

Exercise 3.34: Given that p1 and p2 point to elements in the same array, what does the following code do? Are there values of p1 or p2 that make this code illegal?

p1 += p2 - p1;

将p1移到和p2相同的位置,當p1和p2不是指向同一類型的指針則非法。

Exercise 3.35: Using pointers, write a program to set the elements in an

array to zero.

#include<iostream>
using namespace std;
int main(){
	int ia[]={0,1,2,3,4,5,6,7,8,9};
	int *p=ia;
	for(int i=0;i!=10;++i)
	   *(p+i)=0;
	for(int i=0;i!=10;++i)
		cout<<*(p+i)<<' ';	
	return 0;
} 
                

Exercise 3.35: Using pointers, write a program to set the elements in an array to zero.

//Exercise 3.35:  Using  pointers,  write  a  program  to  set  the elements in anarray to zero.
#include<iostream>
#include<vector>
using namespace std;
int main(){
	int ia1[]={0,1,2,3,4,5,6,7,8,9};
	int ia2[]={1,2,3,4,5,6,7,8,9,10};
	bool flag=1;
	if((end(ia1)-begin(ia1))!=(end(ia2)-begin(ia2))){
		flag=0;
	}else{
		for(int t=0;t<end(ia1)-begin(ia1);++t){
			if(ia1[t]!=ia2[t])
			  flag=0;
		}
}
	
	if(flag){
		cout<<"these two arrays are equal"<<endl;
	}
	else{
		cout<<"these two array are unequal"<<endl;
	}
	vector<int> iv1={0,1,2,3,4,5,6,7,8,9},iv2={0,1,2,3,4,5,6,7,8,9};
	if(iv1==iv2){
		cout<<"these two vectors are equal"<<endl;
    }else{
    	cout<<"these two vectors are unequal"<<endl;
	}


	return 0;
} 
                

Exercise 3.37: What does the following program do?

const char ca[] = {'h', 'e', 'l', 'l', 'o'};
const char *cp = ca;
while (*cp) {
    cout << *cp << endl;
    ++cp;
}
                

列印出

h

e

l

l

o

Exercise 3.39: Write a program to compare two strings. Now write a program to compare the values of two C-style character strings.

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main(){
	string str1="str1",str2="str2";
	if(str1==str2)
		cout<<"str1==str2"<<endl;
	else if(str1>str2)
		cout<<"str1>str2"<<endl;
	else
	    cout<<"str1<str2"<<endl;
	char *char1="*char1",*char2="*char2";
	if(strcmp(char1,char2)==0)
	    cout<<"*char1=*char2";
	else if(strcmp(char1,char2)>0)
		cout<<"*char1>*char2"<<endl;
	else
	    cout<<"*char1<*char2"<<endl;
	return 0;
}
                

Exercise 3.40: Write a program to define two character arrays initialized from string literals. Now define a third character array to hold the concatenation of the two arrays. Use strcpy and strcat to copy the two arrays into the third.

#include<iostream>
#include<cstring>
using namespace std;
int main(){
	char *cstr1="str1",*cstr2="str2",cstr3[20];
	strcpy(cstr3,cstr1);
	strcat(cstr3,cstr2);
	cout<<cstr1<<'+'<<cstr2<<'='<<cstr3<<endl;
	return 0;
}
                

Exercise 3.41: Write a program to initialize a vector from an array of ints.

#include<iostream>
#include<vector>
using namespace std;
int main(){
   int ia[12]={0,1,2,3,4,5,6,7,8,9,10,11};
   vector<int> iv(begin(ia),end(ia));
   return 0; 
}
                

Exercise 3.42: Write a program to copy a vector of ints into an array of ints.

#include<iostream>
#include<vector>
using namespace std;
int main(){
   int ia[12];
   vector<int> iv={0,1,2,3,4,5,6,7,8,9,10,11};
   size_t t=0;
   for(int i:iv)
      ia[t++]=i; 	
    return 0; 
}
                

Exercise 3.43: Write three different versions of a program to print the elements of ia. One version should use a range for to manage the iteration, the other two should use an ordinary for loop in one case using subscripts and in the other using pointers. In all three programs write all the types directly. That is, do not use a type alias, auto, or decltype to simplify the code.

#include<iostream>
using namespace std;
int main(){
	int ia[3][4]={0,1,2,3,4,5,6,7,8,9,10,11};
	//version 1 range for
	for(int (&row)[4]:ia)
	   for(int col:row)
	      cout<<col<<' ';
	cout<<endl;
	//version 2 using subscrips
	for(size_t i=0;i<3;++i)
		for(size_t j=0;j<4;++j)
			cout<<ia[i][j]<<' ';
	cout<<endl;
	//version 3 using pointers
	for(int (*p)[4]=ia;p!=ia+3;++p)
		for(int *q=*p;q!=*p+4;++q)
			cout<<*q<<' ';
	return 0;
} 
                

Exercise 3.44: Rewrite the programs from the previous exercises using a type alias for the type of the loop control variables.

typedef int int_array[4];//or using int_array=int[4];
	//version 1 range for
	for(int_array &row:ia)
	   for(int col:row)
	      cout<<col<<' ';
	cout<<endl;
//version 3 using pointers
	for(int_array *p=ia;p!=ia+3;++p)
		for(int *q=*p;q!=*p+4;++q)
			cout<<*q<<' ';
                

Exercise 3.45: Rewrite the programs again, this time using auto.

//version 1 range for
	for(auto &row:ia)
	   for(auto col:row)
	      cout<<col<<' ';
	//version 3 using pointers
	for(auto *p=ia;p!=ia+3;++p)
			for(auto*q=*p;q!=*p+4;++q)
				cout<<*q<<' ';
                

繼續閱讀