Grammar
The range for statement iterates through each element in the given sequence and performs some action on each value in the sequence, in the form of syntax:
forexpression) statement
which
The expression section is an object that must be a sequence, such as an initial list of values enclosed in curly braces, an array, or an object of a type such as a vector or a string. The common feature of these types is the begin and end members that have the ability to return iterators .
The declaration section is responsible for defining a variable that will be used to access the underlying element in the sequence. For each iteration, the variables of the declaration section are initialized to the next element value in the expression section. The simplest way to ensure type compatibility is to use the auto type specifier .
Although we usually call new T [] allocating memory as "dynamic array", it is important to remember that the dynamic array we are talking about is not an array type. When assigning an array with new, we do not get an object of an array type, but instead get a pointer to the type of the array element. Because the allocated memory is not an array type, begin or end cannot be called on a dynamic array. For the same reason, you cannot use the scope for statement to manipulate elements in a dynamic array.
Example 1
Use the range for statement and the ISPUNCT function to count the number of punctuation in a string object:
size_t cntPunct(string s) { decltype0// punct_cnt 的类型和s.size()的返回类型一样 for (auto c : s) if (ispunct(s)) ++punct_cnt; return punct_cnt;}
Example 2
If you want to change the value in an Expression object, you must define the loop variable as a reference type. With this reference, we can change the element it binds to.
To rewrite a string to uppercase:
void string_toupper(string &s) { for (auto &c : s) toupper(c);}
Example 3
If we want to use a reference and do not want to change the original value, then we can use the const reference.
To print a string:
void string_print(string &s) { for (constauto &c : s) std::cout" ";}
Reference documents:
"C + + Primer (fifth edition)"
C + + Learning: scope for (range for) statement