C ++ learning: range for (range for) Statements
Syntax
The range for statement traverses each element in a given sequence and performs an operation on each value in the sequence. The syntax format is:
for (declaration : expression) statement
Where:
The expression part is an object and must be a sequence. For example, an initial value list, an array, a vector, or a string enclosed in curly brackets. The common characteristics of these types are:Has the begin and end members that can return the iterator.
The declaration part defines a variable that will be used as the basic element in the access sequence. During each iteration, the variables in the declaration part are initialized to the next element value in the expression part.The simplest way to ensure type compatibility is to use the auto type specifier..
Although we usually call the memory allocated by new T [] as a "dynamic array", it is very important to remember that the dynamic array we call is not an array type. When an array is allocated with new, we do not get an array object, but get a pointer of the array element type. Because the allocated memory is not an array type, you cannot call begin or end for dynamic arrays. For the same reason, the range for statement cannot be used to process elements in a dynamic array.
Example 1
Use the range for statement and ispunct function to count the number of punctuation marks in the string object:
Size_t cntPunct (string s) {decltype (s. size () punct_cnt = 0; // punct_cnt type and s. the return type of size () is the same as that of for (auto c: s) if (ispunct (s) ++ punct_cnt; return punct_cnt ;}
Example 2
To change the value in the expression object, you must define the cyclic variable as the reference type. With this reference, we can change the elements it binds.
Rewrite the string to uppercase letters:
void string_toupper(string &s) { for (auto &c : s) c = toupper(c);}
Example 3
If we want to use the reference and do not want to change the original value, we can use the const reference.
Print string:
void string_print(string &s) { for (const auto &c : s) std::cout << c << ;}