之前自己参照Effective Modern C++的思想,想用auto代替遍历,发现逆序的时候会有问题;
对于逆序常规便利,会因为size_t为无符号数,0-1后并不是-1,而是新的无符号数,发生下溢,因此无法通过常规方式遍历;
网上老哥有两种方案:
1.使用n作为起始遍历索引:
这里就能保证直接访问到0元素,巧妙的避开了下溢问题;
vector<int>vec(4, 4);
for (auto i = vec.size(); i-- > 0;) {
cout << vec[i] << endl;
}
2.使用反向迭代器:
使用rbegin()和rend()来进行迭代,后续正序可以参考该方法;
for (auto it = vec.rbegin(); it != vec.rend(); it++) {
cout << *it << endl;
}