C++ Primer 中文第 5 版练习答案 第 3 章 字符串、向量和数组(12~20)

C++ Primer 中文版(第 5 版)练习解答合集

自己写的解答,如有错误之处,烦请在评论区指正!


  1. a. 正确。该向量元素是vector,被默认初始化为空的vector
    b. 错误。类型不匹配;
    c. 正确。该向量由 10 个string组成,每个string都被初始化成"null"
  2. a. 0 个元素;
    b. 10 个元素,都被默认初始化;
    c. 10 个元素,都是 42;
    d. 1 个元素,值是 10;
    e. 2 个元素,分别是 10,42;
    f. 19 个元素,都被默认初始化;
    g. 10 个元素,都是"hi"
#include 
#include  
using namespace std;
int main() {
	int input;
	vector<int> nums;
	while (cin >> input)
		nums.push_back(input);
	for (auto num : nums)
		cout << num << endl;
	return 0;
} 
#include 
#include  
using namespace std;
int main() {
	string input;
	vector<string> svec;
	while (cin >> input)
		svec.push_back(input);
	for (auto s : svec)
		cout << s << endl;
	return 0;
} 
#include 
#include  
#include 
using namespace std;
int main() {
	vector<int> v1, v2(10), v3(10, 42), v4{10}, v5{10, 42};
	vector<string> v6{10}, v7{10, "hi"};
	vector<vector<int> > ivec = {v1, v2, v3, v4, v5};
	vector<vector<string> > svec = {v6, v7};
	int cnt = 1;
	for (auto &i : ivec) {
		cout << "v" << cnt++ << ".size = " << i.size() << endl;
		if (i.size()) {
			for (auto &j : i)
				cout << j << ' ';
			cout << endl; 
		}
		cout << endl; 
	}
	for (auto &i : svec) {
		cout << "v" << cnt++ << ".size = " << i.size() << endl;
		if (i.size()) {
			for (auto &j : i)
				cout << "#" << j << "# ";	// 用 # 来看到空串
			cout << endl;
		} 
	} 
	return 0;
} 

本地输出:

v1.size = 0

v2.size = 10
0 0 0 0 0 0 0 0 0 0

v3.size = 10
42 42 42 42 42 42 42 42 42 42

v4.size = 1
10

v5.size = 2
10 42

v6.size = 10
## ## ## ## ## ## ## ## ## ##
v7.size = 10
#hi# #hi# #hi# #hi# #hi# #hi# #hi# #hi# #hi# #hi#

#include 
#include  
#include 
using namespace std;
int main() {
	string input;
	vector<string> svec;
	while (cin >> input)
		svec.push_back(input);
	for (auto &str : svec)
		for (auto &ch : str)
			ch = toupper(ch);
	for (auto str : svec)
		cout << str << endl; 
	return 0;
} 
  1. 不合法。只有下标所指元素存在时才能用下标来访问它。
vector<int> ivec;
ivec.push_back(42);
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);
// 相邻整数的和
#include 
#include  
using namespace std;
int main() {
	int input;
	vector<int> ivec;
	while (cin >> input)
		ivec.push_back(input);
	if (ivec.size() < 2) {
		cerr << "Please input more numbers!" << endl;
		return 1; 
	}
	for (int i = 0; i != ivec.size() - 1; ++i)
		cout << ivec[i] + ivec[i + 1] << endl; 
	return 0;
} 

// 先输出第一个和最后一个元素的和,以此类推
#include 
#include  
using namespace std;
int main() {
	int input;
	vector<int> ivec;
	while (cin >> input)
		ivec.push_back(input);
	if (ivec.size() < 2) {
		cerr << "Please input more numbers!" << endl;
		return 1; 
	}
	for (int i = 0; i != ivec.size(); ++i)
		cout << ivec[i] + ivec[ivec.size() - i - 1] << endl;
	return 0;
} 

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