C ++ Primer第5版演習の回答[第3章]

C ++ Primer第5版演習の回答[一般リスト]: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

一度に1行ずつ読んでください:

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

一度に1つの単語を読んでください:

#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の読み取りと同様に、文字列オブジェクトは最初の空白を無視し、最初の実際の文字から次の空白に遭遇するまで開始します。
* getline(is、s)の読み取りと同様に、文字列オブジェクトは、改行文字が検出されるまで、入力ストリームから文字を読み取ります。

3.43.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 isastring」が出力されます。

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は文字列オブジェクト内の文字への参照であり、sは定数です。したがって、forループ内のコードがcの値を再割り当てすると、それは違法になり、cの値が変更されない場合、それは合法になります。

3.12

(a)C ++ 11のリーガル(b)違法で異なるタイプ(c)リーガル

3.13

vector <int> v1; //サイズ:0、  値なし。
vector <int> v2(10); //サイズ:10、値:0
vector <int> v3(10、42); //サイズ:10、値:42
vector <int> v4 {10}; //サイズ:1、値:10
vector <int> v5 {10、42}; //サイズ:2、値:
10、42 vector <string> v6 {10}; //サイズ:10、値: ""
vector <string> v7 {10、 "hi"}; //サイズ:10、値: "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

3つのタイプがあります:

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
score [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

2つのポインターを減算すると、(同じ配列内の)2つのポインター間の距離を示すことができ、ポインターに整数を追加すると、ポインターを特定の位置に移動することを示すこともできます。ただし、2つのポインターを追加しても論理的な意味はないため、2つのポインターを追加することはできません。

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