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

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

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


#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.begin(); i != ivec.end(); ++i) {
		cout << "v" << cnt++ << ".size = " << i->size() << endl;
		if (i->size()) {
			for (auto j = i->begin(); j != i->end(); ++j)
				cout << *j << ' ';
			cout << endl; 
		}
		cout << endl; 
	}
	for (auto i = svec.begin(); i != svec.end(); ++i) {
		cout << "v" << cnt++ << ".size = " << i->size() << endl;
		if (i->size()) {
			for (auto j = i->begin(); j != i->end(); ++j)
				cout << "#" << *j << "# ";
			cout << endl; 
		}
		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 
#include 
using namespace std;
int main() {
	string input;
	vector<string> svec;
	while (getline(cin, input))
		svec.push_back(input);
	if (svec.begin() != svec.end())
		for (auto it = (svec[0]).begin(); it != (svec[0]).end(); ++it)
			cout << (char)toupper(*it);
	cout << endl;
	return 0;
}
#include 
#include 
using namespace std;
int main(){
	vector<int> nums(10,4);
	for (auto it = nums.begin(); it != nums.end(); ++it){
		*it *= 2;
		cout << *it << 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 (auto it = ivec.begin(); it != ivec.end() - 1; ++it)
		cout << *it + *(it + 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 (auto it = ivec.begin(); it != ivec.end(); ++it)
		cout << *it + *(ivec.end() - (it - ivec.begin()) - 1) << endl;
	return 0;
}
#include 
#include  
using namespace std;
int main() {
	vector<unsigned> scores(11, 0);
	unsigned grade;
	while (cin >> grade) {
		if (grade <= 100)
			++*(scores.begin() + grade / 10);
	}
	for (auto it = scores.begin(); it != scores.end(); ++it)
		cout << *it << ' ';
	return 0;
}
  1. mid = beg + (end - beg) / 2是更安全的写法,防止beg + end的运算结果过大而溢出。

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