05 May 2023

C++ 核心指南目录

“Prefer a for-statement to a while-statement when there is an obvious loop variable”

理由

可读性:循环的完整逻辑在最前面就明了。可以限制循环变量的范围。

例子

std::vector<int> vec{1, 2, 3, 4, 5};
for (gsl::index i = 0; i < vec.size(); i++) {
    std::cout << vec[i] << "\n";
}
1
2
3
4
5

坏例子

std::vector<int> vec{1, 2, 3, 4, 5};
int i = 0;
while (i < vec.size()) {
    std::cout << vec[i] << "\n";
    i++;
}
1
2
3
4
5