系统环境: windows 10 1703
编译环境:Visual studio 2017
3.21
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
// 以 v2 和 v7 为例
int main()
{
vector<int> v2(10);
vector<string> v7{ 10, "hi" };
for (vector<int>::iterator a = v2.begin(); a != v2.end(); ++a)
{
cout << *a << endl;
}
for (auto b = v7.begin(); b != v7.end(); ++b)
{
cout << *b << endl;
}
return 0;
}
3.22
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
int main()
{
vector<string> text{5, "randomstring"};
for (auto it = text.begin(); it != text.end() && !it->empty(); ++it)
{
for (auto &a : *it)
{
a = toupper(a);
}
}
for (auto it2 = text.begin(); it2 != text.end() && !it2->empty(); ++it2)
{
cout << *it2 << endl;
}
return 0;
}
3.23
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
int main()
{
vector<int> ivec;
cout << "Enter ten integers: " << endl;
int i;
while (cin >> i)
{
ivec.push_back(i);
}
for (auto b = ivec.begin(); b != ivec.end(); ++b)
{
*b *= 2;
cout << *b << endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
//相邻之和
int main()
{
vector<int> ivec;
int i;
while (cin >> i)
{
ivec.push_back(i);
}
auto b = ivec.begin();
auto e = ivec.end();
for (b; b != (e - 1); ++b)
{
cout << (*b + *(b + 1)) << endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
//首尾之和
int main()
{
vector<int> ivec;
int i;
while (cin >> i)
{
ivec.push_back(i);
}
auto b = ivec.begin();
auto e = (ivec.end() - 1);
for (b; b <= e; ++b)
{
if (b != e)
{
cout << (*b + *(e)) << endl;
--e;
}
else
{
cout << "This is the middle number: " << *b << endl;
}
}
return 0;
}
3.25
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
int main()
{
vector<int> result(11, 0);
auto b = result.begin();
unsigned i;
while (cin >> i)
{
if (i <= 100)
{
int n = i / 10;
*(b + n) += 1;
}
}
for (auto a : result)
{
cout << a << endl;
}
return 0;
}
3.26
因为前者会避免溢出。在后者的计算过程中,在 (beg + end) 这一步中有可能出现比 end 大的数,而前者的计算过程就不会出现这种风险。
3.27
(a) 非法,buf_size 不是常量表达式;
(b) 合法;
(c) 非法,txt_size() 不是常量表达式;
(d) 非法,没有空间存放空字符。
3.28
sa 空字符
ia 0
sa2 空字符
ia2 undefined
// 中文版 p40 有详细说明
3.29
相较于 vector,数组的大小在定义时就固定了。数组的大小固定不变,不能随意向数组中增加元素,损失了一些灵活性。