《C++ Primer》第五版课后习题解答_第四章(1)(01-20)
系统环境: windows 10 1703
编译环境:Visual studio 2017
4.1
105
4.2
(a)
*vec.begin(); *(vec.begin());(b)
*vec.begin() + 1; (*(vec.begin())) + 1;
4.3
我觉得值得讨论。对于不熟悉 C++ 的人来说,对于潜在的可能造成风险的地方有可能会增加变成成本。但若是精通 C++ 的人,可以很自如地规避潜在风险,那么这种权衡就是增加代码生成效率的很好的手段。(当然还是假定使用的人都精通 C++ 的这一条规则更加省事)
4.4
((12 / 3) * 4) + (5 * 15) + (24 % 4 ) / 2
#include <iostream> using std::cout; using std::cin; using std::endl; int main() { int i = 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2; int j = ((12 / 3) * 4) + (5 * 15) + ((24 % 4) / 2); cout << "i " << i << " j " << j << endl; return 0; }输出 i 91 j 91
4.5
(a) -86
(b) -18
(c) 0
(d) -2
4.6
#include <iostream> using std::cout; using std::cin; using std::endl; int main() { int i; cout << "Enter an integer: " << endl; cin >> i; if (i % 2 == 0) { cout << "The input integer is even." << endl; } else { cout << "The input integer is odd." << endl; } return 0; }
4.7
#include <iostream> using std::cout; using std::cin; using std::endl; int main() { short short_i = 32767; short_i += 1; unsigned un_i = 0; un_i -= 1; unsigned short unshort_i = 65535; unshort_i += 1; cout << short_i << " " << un_i << " " << unshort_i << endl; return 0; }输出为 -32768 4294967295 0
4.8
逻辑与:先判断左侧的对象,当左侧为真时再判断右侧的对象;
逻辑或:先判断左侧的对象,当左侧为假时再判断右侧的对象;
相等性:两侧对象的求值顺序未定义。
4.9
先判断左侧,cp 为指向一个常量字符数组的指针,非空,故为真;
再判断右侧,*cp 为常量字符数组的第一个元素,为 ‘H’,非空,故为真;
逻辑与两侧均为真,故此表达式为真。
4.10
#include <iostream> #include <vector> using std::cout; using std::cin; using std::endl; using std::vector; int main() { int i = 0; vector<int> ivec = {}; while (cin >> i && i != 42) //读取输入,遇到42则停止读取 { ivec.push_back(i);//将读取到的输入放进 vector 中 } for (auto &a : ivec) { cout << a << endl; } return 0; }
4.11
a > b && b > c && c > d;
4.12
i != j < k 等价于 i != (j < k),即先判断 j, k 的关系,再将其结果和 i 进行比较。
4.13
(a) d = 3, i = 3
(b) d = 3.5, i = 3
4.14
if (42 = i) // error, 条件语句非法,字面值为右值,不能放在赋值运算符左侧 if (i = 42) // 条件语句始终为真
4.15
非法,pi 为指针,和其他两个变量的数据类型不同,不能连续赋值,可改为:
dval = ival = 0; pi = 0;
4.16
(a) 预期可能是比较输入值和 0 的大小关系,故可以修改为:
if ((p = getPtr()) != 0)(b) 预期可能是判断 i 是否等于 1024,故可以修改为:
if (i == 1024)
4.17
前至递增运算符:将运算对象加一,并返回递增后的值;
后置递增运算符:将运算对象加一,并返回递增前的值。
4.18
若使用前置递增运算符,则会先将 pbeg 向前移动一个元素,再输出其指向的元素。
从 v 的第二个元素开始输出,到 end 为止。
4.19
(a) (ptr != 0) && (*(ptr++)) 先判断 ptr 是否为空指针,再判断 ptr 所指的元素是否为空,再将 ptr 向前移动一个元素;
(b) ival++ && ival 将 ival 递增一,再判断递增前的 ival (逻辑与左侧),再判断递增后的 ival(逻辑与右侧);
(c) vec[ival++] <= vec[ival], 未定义行为(undefined behavior),无法判断右侧的 ival 是递增前还是递增后,可修改为:
vec[ival + 1] <= vec[ival]
4.20
(a) 取 iter 的元素,再将 iter 向前移动一位;
(b) 不合法,取 iter 的元素,做后置递增运算,因为 iter 的元素是字符串,故不能递增;
(c) 不合法,表达式实际上为 *(iter.empty()),对后者解引用无效;
(d) 判断 iter 的元素是否为空;
(e) 不合法,字符串不能递增;
(f) 判断 iter 的元素是否为空,再将 iter 向前移动一位。