C++Primer第五版 习题答案 【第三章】

C++Primer第五版 习题答案 【总目录】:https://blog.csdn.net/Dust_Evc/article/details/114334124

3.1

1.4.1节:

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
	int sum = 0;
	for (int val = 1; val <= 10; ++val) sum += val;

	cout << "Sum of 1 to 10 inclusive is " << sum << endl;
	
	return 0;
}

2.6.2节:

#include <iostream>
#include <string>
#include "exercise2_42.h"

using std::cin;
using std::cout;
using std::endl;
using std::cerr;

int main()
{
    Sales_data data1, data2;

    double price = 0;  

    cin >> data1.bookNo >> data1.units_sold >> price;
    
    data1.revenue = data1.units_sold * price;

    cin >> data2.bookNo >> data2.units_sold >> price;
    data2.revenue = data2.units_sold * price;

    if (data1.bookNo == data2.bookNo)
    {
        unsigned totalCnt = data1.units_sold + data2.units_sold;
        double totalRevenue = data1.revenue + data2.revenue;

        cout << data1.bookNo << " " << totalCnt
            << " " << totalRevenue << " ";
        if (totalCnt != 0)
            cout << totalRevenue / totalCnt << endl;
        else
            cout << "(no sales)" << endl;

        return 0;  
    }
    else
    {  
        cerr << "Data must refer to the same ISBN" << endl;
        return -1; 
    }
}

3.2

一次读入一行:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::getline;

int main()
{
	string s;
	while (getline(cin,s))
	{
		cout << s << endl;
	}
	return 0;
}

一次读入一个词:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s;
	while (cin >> s)
	{
		cout << s << endl;
	}
	return 0;
}

3.3

类似 is >> s 的读取,string对象会忽略开头的空白并从第一个真正的字符开始,直到遇见下一空白为止。
* 类似 getline(is, s) 的读取,string对象会从输入流中读取字符,直到遇见换行符为止。

3.4

比较大的:

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		if (str1 == str2)
			cout << "The two strings are equal." << endl;
		else
			cout << "The larger string is " << ((str1 > str2) ? str1 : str2);
	}

	return 0;
}

长度大的:

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		if (str1.size() == str2.size())
			cout << "The two strings have the same length." << endl;
		else
			cout << "The longer string is " << ((str1.size() > str2.size()) ? str1 : str2) << endl;
	}

	return 0;
}

3.5

未隔开的:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string result, s;
	while (cin >> s)
	{
		result += s;
	}
	cout << result << endl;

	return 0;
}

隔开的:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string result, s;
	while (cin >> s)
	{
		result += s + " ";
	}
	cout << result << endl;

	return 0;
}

3.6

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this is a string";			    
	for (auto &x : s)
	{
		x = 'X';
	}

	cout << s << endl;
	return 0;
}

3.7


#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this is a string";

	for (char x : s)
	{
		x = 'X';
	}

	cout << s << endl;
	return 0;
}

并未将字符串用X替换掉,而是输出原字符串"this is a string"。

3.8

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this is a string";

	decltype(s.size()) i = 0;
	while (i != s.size())
	{
		s[i] = 'X';
		++i;
	}
	cout << s << endl;
	for (i = 0; i != s.size(); ++i)
	{
		s[i] = 'Y';
	}
	cout << s << endl;
	return 0;
}

3.9

不合法。使用下标访问空字符串是非法行为

3.10

#include <iostream>
#include <string>
#include <cctype>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this, is. a :string!";
	string result;

	for (auto x : s)
	{
		if (!ispunct(x))
		{
			result += x;
		}
	}

	cout << result << endl;
	return 0;
}

3.11

要根据for循环中的代码来看是否合法,c是string 对象中字符的引用,s是常量。因此如果for循环中的代码重新给c赋值就会非法,如果不改变c的值,那么合法。

3.12

(a) 在C++11当中合法  (b) 不合法,类型不一样   (c) 合法

3.13

vector<int> v1;                          // size:0,  no values.
vector<int> v2(10);                   // size:10, value:0
vector<int> v3(10, 42);             // size:10, value:42
vector<int> v4{ 10 };                 // size:1,  value:10
vector<int> v5{ 10, 42 };           // size:2,  value:10, 42
vector<string> v6{ 10 };            // size:10, value:""
vector<string> v7{ 10, "hi" };    // size:10, value:"hi"

3.14

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main()
{
	vector<int> v;
	int i;
	while (cin >> i)
	{
		v.push_back(i);
	}
	return 0;
}

3.15

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<string> v;
	string i;
	while (cin >> i)
	{
		v.push_back(i);
	}
	return 0;
}

3.16

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<int> v1;         // size:0,  no values.
	vector<int> v2(10);     // size:10, value:0
	vector<int> v3(10, 42); // size:10, value:42
	vector<int> v4{ 10 };     // size:1,  value:10
	vector<int> v5{ 10, 42 }; // size:2,  value:10, 42
	vector<string> v6{ 10 };  // size:10, value:""
	vector<string> v7{ 10, "hi" };  // size:10, value:"hi"

	cout << "v1 size :" << v1.size() << endl;
	cout << "v2 size :" << v2.size() << endl;
	cout << "v3 size :" << v3.size() << endl;
	cout << "v4 size :" << v4.size() << endl;
	cout << "v5 size :" << v5.size() << endl;
	cout << "v6 size :" << v6.size() << endl;
	cout << "v7 size :" << v7.size() << endl;

	cout << "v1 content: ";
	for (auto i : v1)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v2 content: ";
	for (auto i : v2)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v3 content: ";
	for (auto i : v3)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v4 content: ";
	for (auto i : v4)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v5 content: ";
	for (auto i : v5)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v6 content: ";
	for (auto i : v6)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v7 content: ";
	for (auto i : v7)
	{
		cout << i << " , ";
	}
	cout << endl;
	return 0;
}

3.17

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<string> v;
	string s;

	while (cin >> s)
	{
		v.push_back(s);
	}

	for (auto &str : v)			//str引用vector中各元素(这里各元素类型为String)
	{
		for (auto &c : str)		//c引用vector中各元素的各字符(这里类型为char)
		{
			c = toupper(c);		//将各字符转为大写
		}
	}

	for (auto i : v)		// 将vector中各元素内的String逐个输出
	{
		cout << i << endl;
	}
	return 0;
}

3.18

不合法。应改为:

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

3.19

如下三种:

vector<int> ivec1(10, 42);
vector<int> ivec2{ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
vector<int> ivec3;
for (int i = 0; i < 10; ++i)
	ivec3.push_back(42);

第一种方式最好。

3.20

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<int> ivec;
	int i;
	while (cin >> i)
	{
		ivec.push_back(i);
	}
	cout << "相邻整数的和:" << endl;

	for (int i = 0; i < (ivec.size() - 1); ++i)
	{
		cout << ivec[i] + ivec[i + 1] << endl;
	}

	//---------------------------------
	cout << "---------------------------------" << endl;
	cout << "首位对称整数的和:" << endl;

	int m = 0;
	int n = ivec.size() - 1;
	while (m < n)
	{
		cout << ivec[m] + ivec[n] << endl;
		++m;
		--n;
	}
	return 0;
}

3.21

#include <vector>
#include <iterator>
#include <string>
#include <iostream>

using std::vector;
using std::string;
using std::cout;
using std::endl;

void check_and_print(const vector<int>& vec)
{
	cout << "size: " << vec.size() << "  content: [";
	for (auto it = vec.begin(); it != vec.end(); ++it)
		cout << *it << (it != vec.end() - 1 ? "," : "");
	cout << "]\n" << endl;
}

void check_and_print(const vector<string>& vec)
{

	cout << "size: " << vec.size() << "  content: [";
	for (auto it = vec.begin(); it != vec.end(); ++it)
		cout << *it << (it != vec.end() - 1 ? "," : "");
	cout << "]\n" << endl;
}

int main()
{
	vector<int> v1;
	vector<int> v2(10);
	vector<int> v3(10, 42);
	vector<int> v4{ 10 };
	vector<int> v5{ 10, 42 };
	vector<string> v6{ 10 };
	vector<string> v7{ 10, "hi" };

	check_and_print(v1);
	check_and_print(v2);
	check_and_print(v3);
	check_and_print(v4);
	check_and_print(v5);
	check_and_print(v6);
	check_and_print(v7);

	return 0;
}

3.22

#include <iostream>
#include <vector>
#include <cctype>
#include <string>

using namespace std;

int main()
{
	vector<string> text;
	text.push_back("aaaaaaaaaa aaaaaaaaa aaaaaa");
	text.push_back("");
	text.push_back("bbbbbbbbbbbbbb bbbbbbbbbbb bbbbbbbbbbbbb");

	for (auto it = text.begin(); it != text.end() && !it->empty(); ++it)
	{
		for (auto &c : *it)
		{
			c = toupper(c);
		}
	}

	for (auto it : text)
	{
		cout << it << endl;
	}
	return 0;
}

3.23

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> ivec(10, 30);

	for (auto &it : ivec)
	{
		it = it * 2;
		cout << it << endl;
	}

	return 0;
}

3.24

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<int> ivec;
	int i;
	while (cin >> i)
	{
		ivec.push_back(i);
	}
	cout << "相邻整数的和:" << endl;

	for (auto it = ivec.begin(); it != ivec.end() - 1; ++it)
	{
		cout << *it + *(it + 1) << endl;
	}

	//---------------------------------
	cout << "---------------------------------" << endl;
	cout << "首位对称整数的和:" << endl;

	auto it1 = ivec.begin();
	auto it2 = ivec.end() - 1;
	while (it1 < it2)
	{
		cout << *it1 + *it2 << endl;
		++it1;
		--it2;
	}
	return 0;
}

3.25

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<unsigned > scores;  //类型unsigned int 可以缩写为unsigned
	vector<unsigned > grade(11, 0);
	unsigned  i;
	while (cin >> i)    //原数据为:42 65 95 100 39 67 95 76 88 76 83 92 76 93
	{
		scores.push_back(i);
	}

	cout << "各成绩对应的分段为:";
	for (auto it = scores.begin(); it != scores.end(); ++it)
	{
		if (*it <= 100)
		{
			++grade[*it / 10];
			cout << *it / 10 << (it != scores.end() - 1 ? " " : "");
		}		
	}
	cout << endl;

	cout << "各分段总数为:";
	for (auto cnt : grade)
	{
		cout  << cnt << " ";
	}
	cout << endl;
	return 0;
}

3.26

因为迭代器支持的运算只有 ` - ` ,而没有 ` + ` 。` end - beg ` 意思是相距若干个元素,将之除以2然后与beg相加,表示将beg移动到一半的位置。

3.27

(a) 非法。维度必须是一个常量表达式。
(b) 合法。
(c) 非法。txt_size() 的值必须要到运行时才能得到,且可能未负值。
(d) 非法。数组的大小应该是12。

3.28

数组的元素会被默认初始化。

sa 的元素值全部为空字符串,ia 的元素值全部为0。

sa2 的元素值全部为空字符串,ia2 的元素值全部未定义

3.29

数组的大小是确定的;
不能随意增加元素;
不允许拷贝和赋值。

3.30

当 ix 增长到 10 的时候,ia[ix] 的下标越界。

3.31

#include <vector>
#include <iostream>

int main()
{
	int arr[10];
	for (unsigned i = 0; i <= 9; ++i)
		arr[i] = i;	
	for (auto val : arr)
		std::cout << val << " ";
	std::cout << std::endl;
	return 0;
}

3.32

#include <iostream>
#include <vector>

using std::cout; 
using std::endl; 
using std::vector;

int main()
{
	// array
	int arr[10];
	for (int i = 0; i < 10; ++i) 
		arr[i] = i;
	int arr2[10];
	for (int i = 0; i < 10; ++i)  //数组需逐元素拷贝赋值
		arr2[i] = arr[i];	

	// vector
	vector<int> v(10);
	for (int i = 0; i < 10; ++i) 
		v[i] = arr[i];
	vector<int> v2(v);	//向量可以直接将v赋给v2
	for (auto i : v2) 
		cout << i << " ";
	cout << endl;

	return 0;
}

3.33

如果是这种形式:unsigned scores[11];
则会对数组中各元素进行默认初始化为:3435973836

3.34

将 p1 移动到 p2 的位置。任何情况下都合法。

3.35

#include <iostream>

using std::cout;
using std::endl;

int main()
{
	const int size = 10;
	int arr[size];
	for (auto ptr = arr; ptr != arr + size; ++ptr) 
		*ptr = 0;

	for (auto i : arr) 
		cout << i << " ";
	cout << endl;

	return 0;
}

3.36

#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

bool compare(int* const pb1, int* const pe1, int* const pb2, int* const pe2)
{
	if ((pe1 - pb1) != (pe2 - pb2)) 
		return false;
	else
	{
		for (int* i = pb1, *j = pb2; (i != pe1) && (j != pe2); ++i, ++j)
		if (*i != *j) return false;
	}

	return true;
}

int main()
{
	int arr1[3] = { 0, 1, 2 };
	int arr2[3] = { 0, 2, 4 };

	if (compare(begin(arr1), end(arr1), begin(arr2), end(arr2)))
		cout << "The two arrays are equal." << endl;
	else
		cout << "The two arrays are not equal." << endl;

	cout << "==========" << endl;

	vector<int> vec1 = { 0, 1, 2 };
	vector<int> vec2 = { 0, 1, 2 };

	if (vec1 == vec2)
		cout << "The two vectors are equal." << endl;
	else
		cout << "The two vectors are not equal." << endl;

	return 0;
}

3.37

会将ca 字符数组中的元素打印出来。但是因为没有空字符的存在,程序不会退出循环。

3.38

将两个指针相减可以表示两个指针(在同一数组中)相距的距离,将指针加上一个整数也可以表示移动这个指针到某一位置。但是两个指针相加并没有逻辑上的意义,因此两个指针不能相加。

3.39

#include <iostream>
#include <string>

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

int main()
{
	string s1("aaaaaaaaaa"), s2("bbbbbbbbbb");
	if (s1 == s2)
		cout << "same string." << endl;
	else if (s1 > s2)
		cout << "aaaaaaaaaa > bbbbbbbbbb" << endl;
	else
		cout << "aaaaaaaaaa < bbbbbbbbbb" << endl;

	cout << "=========" << endl;

	const char* cs1 = "aaaaaaaaaa";
	const char* cs2 = "bbbbbbbbbb";
	auto result = strcmp(cs1, cs2);
	if (result == 0)
		cout << "same string." << endl;
	else if (result < 0)
		cout << "aaaaaaaaaa < bbbbbbbbbb" << endl;
	else
		cout << "aaaaaaaaaa > bbbbbbbbbb" << endl;

	return 0;
}

3.40

#include <iostream>
#include <cstring>

const char cstr1[] = "Hello";
const char cstr2[] = "world!";

int main()
{
	char cstr3[100];

	strcpy(cstr3, cstr1);
	strcat(cstr3, " ");
	strcat(cstr3, cstr2);

	std::cout << cstr3 << std::endl;
}

3.41

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	vector<int> v(begin(arr), end(arr));

	for (auto i : v) cout << i << " ";
	cout << endl;

	return 0;
}

3.42

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int arr[10];
	for (int i = 0; i != v.size(); ++i) 
		arr[i] = v[i];

	for (auto i : arr) cout << i << " ";
	cout << endl;

	return 0;
}

3.43

#include <iostream>

using std::cout;
using std::endl;

int main()
{
	int arr[3][4] =
	{
		{ 0, 1, 2, 3 },
		{ 4, 5, 6, 7 },
		{ 8, 9, 10, 11 }
	};

	// range for
	for (const int(&row)[4] : arr)
		for (int col : row) cout << col << " ";

	cout << endl;

	// for loop
	for (size_t i = 0; i != 3; ++i)
		for (size_t j = 0; j != 4; ++j) cout << arr[i][j] << " ";

	cout << endl;

	// using pointers.
	for (int(*row)[4] = arr; row != arr + 3; ++row)
		for (int *col = *row; col != *row + 4; ++col) cout << *col << " ";

	cout << endl;

	return 0;
}

3.44

#include <iostream>

using std::cout; 
using std::endl;

int main()
{
	int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

	using int_array = int[4];

	for (int_array& p : ia)
		for (int q : p)
			cout << q << " ";
	cout << endl;

	for (size_t i = 0; i != 3; ++i)
		for (size_t j = 0; j != 4; ++j)
			cout << ia[i][j] << " ";
	cout << endl;

	for (int_array* p = ia; p != ia + 3; ++p)
		for (int *q = *p; q != *p + 4; ++q)
			cout << *q << " ";
	cout << endl;

	return 0;
}

3.45

#include <iostream>

using std::cout;
using std::endl;

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 << q << " ";
	cout << endl;

	for (auto i = 0; i != 3; ++i)
		for (auto j = 0; j != 4; ++j)
			cout << ia[i][j] << " ";
	cout << endl;

	for (auto p = ia; p != ia + 3; ++p)
		for (auto q = *p; q != *p + 4; ++q)
			cout << *q << " ";
	cout << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/Dust_Evc/article/details/114159821