A for loop is a repetition control structure that allows you to efficently write a loop that needs to execute a specific number of times.
-
normal
for (init; condition; increment){ statement(s); }which can also expressed :
for (initialization; condition; increase) statement;The three fileds in a for-loop are optional. They can be left empty, but in all cases the semicolon signs between them are required.
A loop with no condition is equivalent to a loop with
trueas condition (i.e., an infinite loop).It is valid that more than a single expression as any of
initialization,condition, orstatement. -
Range-based for loop
The for-loop has another syntax, which is used exclusively with ranges:
for (declaration : range) statement;This kind of
forloop iterates over all the elements inrange, wheredeclarationdeclares some variable able to take the value of an element in this range. Ranges are sequences of elements, including arrays, containers, and any other type supporting the functionsbeginandend.#include <iostream> #include <string> using namespace std; int main() { string str {"hello"}; for (char c : str) { cout << c; } cout << '\n'; }What precedes the colon (
:) in the for loop is the declaration of acharvariable (the elements in a string are of typechar). We then use this variable,c, in the statement block to represent the value of each of the elements in the range.This loop is automatic and does not require the explicit declaration of any counter variable.
Range based loops usually also make use of type deduction for the type of the elements with auto. Typically, the range-bases loop above can also be written as :
for (auto c : str) cout << c;Here, the type of
cis automatically deduced as the type of the elemets instr.
本文深入探讨了C++中for循环的使用,包括其语法、如何执行特定次数的循环、空条件下的无限循环,以及范围基for循环的使用,特别介绍了如何遍历字符串和容器中的元素。
1万+

被折叠的 条评论
为什么被折叠?



