练习4.31
本节的程序使用了前置版本的递增运算符和递减运算符,解释为什么要用前置版本而不用后置版本。想要使用后置版本的递增递减运算符需要做哪些改动?使用后置版本重写本节程序。
解答:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> ivec{ 1, 2, 3, 4, 5, 6 };
vector<int>::size_type cnt = ivec.size();
for (vector<int>::size_type ix = 0; ix != ivec.size(); ix++, cnt--){
ivec[ix] = cnt;
}
for (auto i : ivec){
cout << i << endl;
}
}
这里个人认为没有什么区别,因为先学的C,所以在刚接触C++的时候还是愿意写成后置形式。
从结果上来看,两个版本的达到的结果是一样的。
哪位朋友可以对这个问题进行更深入的解答,麻烦在评论里面写一下。
2016.0.05修改
引用 这里
We use prefix and not postfix, just because of the Advice: Use Postfix Operators only When Necessary
on §4.5. Increment and Decrement Operators
.
Advice: Use Postfix Operators only When Necessary
Readers from a C background might be surprised that we use the prefix increment in the programs we've written. The reason is simple: The prefix version avoids unnecessary work. It increments the value and returns the incremented version.The postfix operator must store the original value so that it can return the unincremented value as its result. If we don’t need the unincremented value, there’s no need for the extra work done by the postfix operator.
For ints and pointers, the compiler can optimize away this extra work. For more complicated iterator types, this extra work potentially might be more costly. By habitually using the prefix versions, we do not have to worry about whether the performance difference matters. Moreover—and perhaps more importantly—we can express the intent of our programs more directly.
So, it's just a good habits. And there are no changes if we have to be made to use the postfix versions
练习4.32
解释下面这个循环的含义。
constexpr int size = 5;
int ia[size] = {1,2,3,4,5};
for (int *ptr = ia, ix = 0; ix != size && ptr != ia + size; ++ix, ++ptr{/*...*/}
解答:
先初始化了一个长度为5的int数组。
然后,遍历这个数组中的各个元素。
练习4.33
根据4.12节中的表说明下面这条表达式的含义。
someValue? ++x, ++y: --x, --y;
解答:
#include <iostream>
#include <vector>
using namespace std;
int main(){
int someValue = 1;
int x = 0, y = 0;
someValue ? ++x, ++y : --x, --y;
cout << x << endl;
cout << y << endl;
}
当someValue不为0的时候,只会执行++x。
当someValuew为0的时候,会执行--x和--y。