Loops
Quick Notes
Section titled “Quick Notes”for phù hợp khi biết số vòng lặp.
while phù hợp khi lặp tới lúc điều kiện đổi.
Range-based for giúp duyệt container ngắn và ít lỗi index.
Syntax
Section titled “Syntax”for (int i = 0; i < n; ++i) { work(i);}Example
Section titled “Example”std::vector<int> nums = {1, 2, 3};
for (int x : nums) { std::cout << x << ' ';}
for (int& x : nums) { x *= 2;}Loop Types
Section titled “Loop Types”while (ready()) { step();}
do { read();} while (!valid());Common Mistakes
Section titled “Common Mistakes”- Dùng
i <= nkhi index hợp lệ là0..n-1. - Quên cập nhật biến trong
while, gây infinite loop. - Dùng
auto xthay vìauto& xkhi muốn sửa phần tử.
Search Keywords
Section titled “Search Keywords”loops vòng lặp for while do while range based for