C++Primer Fifth Edition Exercise Answers [Chapter Three]

C++Primer Fifth Edition Exercise Answers [General List]: https://blog.csdn.net/Dust_Evc/article/details/114334124

3.1

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

Section 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

Read in one line at a time:

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

Read one word at a time:

#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

Similar to the reading of is >> s, the string object ignores the initial blank and starts from the first real character until it encounters the next blank.
* Similar to the reading of getline(is, s), the string object will read characters from the input stream until a newline character is encountered.

3.4

Relatively large:

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

Longer:

#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

Unseparated:

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

Separated:

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

Instead of replacing the string with X, the original string "this is a string" is output.

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

illegal. Using subscripts to access empty strings is illegal .

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

According to the code in the for loop to see whether it is legal, c is a reference to a character in the string object, and s is a constant. Therefore, if the code in the for loop re-assigns the value of c, it will be illegal, and if the value of c is not changed, it will be legal.

3.12

(a) Legal in C++11 (b) Illegal, different types (c) Legal

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

illegal. Should be changed to:

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

3.19

There are three types:

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

The first way is the best.

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

Because the operations supported by iterators are only `-`, but not `+` . `end-beg` means several elements apart, divide it by 2 and add it to beg, which means to move beg to half of the position.

3.27

(a) Illegal. The dimension must be a constant expression.
(b) Legal.
(c) Illegal. The value of txt_size() cannot be obtained until runtime, and may not be negative.
(d) Illegal. The size of the array should be 12.

3.28

The elements of the array will be initialized by default.

The element values ​​of sa are all empty strings, and the element values ​​of ia are all 0.

The element values ​​of sa2 are all empty strings, and the element values ​​of ia2 are all undefined .

3.29

The size of the array is determined;
elements cannot be added arbitrarily;
copying and assignment are not allowed.

3.30

When ix increases to 10, the subscript of ia[ix] is out of range.

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

If it is in this form: unsigned scores[11];
each element in the array will be initialized by default to: 3435973836

3.34

Move p1 to the position of p2. It is legal under any circumstances.

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

Will print out the elements in the ca character array. But because there is no null character, the program will not exit the loop.

3.38

Subtracting two pointers can indicate the distance between two pointers (in the same array), and adding an integer to the pointer can also indicate moving the pointer to a certain position. But the addition of two pointers has no logical meaning, so two pointers cannot be added.

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

 

Guess you like

Origin blog.csdn.net/Dust_Evc/article/details/114159821