目录
练习3.16题解
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v1; //空的vector对象,元素个数为0
vector<int> v2(10);
vector<int> v3(10, 42);
vector<int> v4{ 10 };
vector<string> s1{ 10 };
vector<string> s2{ 10, "hi" };
vector<string> s3(10, " ");
//输出vector对象中元素的个数
cout << "v1中元素的个数:" << v1.size() << endl;
cout << "v2中元素的个数:" << v2.size() << endl;
cout << "v3中元素的个数:" << v3.size() << endl;
cout << "v4中元素的个数:" << v4.size() << endl;
cout << "s1中元素的个数:" << s1.size() << endl;
cout << "s2中元素的个数:" << s2.size() << endl;
cout << "s3中元素的个数:" << s3.size() << endl;
//使用范围for语句遍历vector对象进行输出
for (auto v : v1)
cout << "v1:" << v << endl;
for (auto v : v2)
cout << "v2:" << v << endl;
for (auto v : v3)
cout << "v3:" << v << endl;
for (auto v : v4)
cout << "v4:" << v << endl;
for (auto v : s1)
cout << "s1:" << v << endl;
for (auto v : s2)
cout << "s2:" << v << endl;
for (auto v : s3)
cout << "s3:" << v << endl;
return 0;
system("pause");
}
练习3.17题解
#include <iostream>
#include <vector>
using namespace std;
int main() {
string str;
vector<string> svec; //空vector对象
//读入一组词并存入svec容器中
while (cin >> str) {
svec.push_back(str);
}
//把所有词都改为大写形式
for (auto& str : svec) {
for (auto& s : str) {
s = toupper(s);
}
}
//输出改变后的结果
for (auto str : svec) {
cout << str << endl;
}
return 0;
system("pause");
}
练习3.18题解
(1)不合法。不能使用下标形式添加对象。由于ivec是个空的vector对象,其中不包含任何元素,故不能使用下标为不存在的元素赋值。
注意:vector对象(以及string对象)的下标运算必须用于访问已存在的元素。
(2)可以利用vector的成员函数push_back向vector对象中添加元素。正确代码如下所示:
vector<int> ivec;
ivec.push_back(42);
练习3.19题解
第一种方式最好。如果给出vector对象所容纳元素的数量及其初始值,选用圆括号进行初始化最好。
注意1:不能用范围for语句为vector对象添加元素,因为范围for语句体内不应改变其所遍历序列的大小
注意2:使用第三种方式,不能预先为vector对象设定大小。因为push_back函数是向vector对象的尾部追加元素。如果预先设定大小为10,v3将会被初始化为10个0,而后再向v3中追加10个10,那么v3的大小就为20了。
vector<int> v1(10, 42);
vector<int> v2 = { 10,10, 10, 10, 10, 10, 10, 10, 10, 10 };
vector<int> v3;
//不能用范围for语句为vector对象添加元素
// 因为范围for语句体内不应改变其所遍历序列的大小
for (decltype(v3.size()) index = 0; index != 10; ++index) {
v3.push_back(10);
}
练习3.20题解
#include <iostream>
#include <vector>
using namespace std;
int main() {
int i = 0;
int sum = 0;
vector<int> ivec; //空vector对象
//读入整数并存入
while (cin >> i) {
ivec.push_back(i);
}
//依次输出每对相邻整数的和
//注意下标越界问题,index的最后取值为ivec.size()-2
for (decltype(ivec.size()) index = 0; index != ivec.size() - 1; ++index) {
sum = ivec[index] + ivec[index + 1];
cout << sum << " ";
sum = 0;
}
//改写:(方法一)依次输出第i个元素和第v.size()-i-1个元素的和
unsigned m = 0, n1 = ivec.size() - 1;
while (m < n1) {
sum = ivec[m] + ivec[n1];
++m;
--n1;
cout << sum << " ";
}
// 如果长度为奇数,单独输出中间按个元素
if (ivec.size() % 2 != 0) {
cout << ivec[ivec.size() / 2] << endl;
}
//改写:(方法二)依次输出第i个元素和第v.size()-i-1个元素的和
unsigned n2 = ivec.size();
for (decltype(ivec.size()) i = 0; i != n2 / 2; ++i) {
sum = ivec[i] + ivec[n2 - i -1];
cout << sum << " ";
sum = 0;
}
//如果n为奇数,单独输出中间那个数
if (n2 % 2 != 0) {
cout << ivec[n / 2] << endl;
}
return 0;
system("pause");
}