我读入了C++ Primer :
If we want to change the value of the characters in a string, we must define the loop variable as a reference type (§ 2.3.1, p. 50). Remember that a reference is just another name for a given object. When we use a reference as our control variable, that variable is bound to each element in the sequence in turn. Using the reference, we can change the character to which the reference is bound.
此外,他们还提供了以下代码:
string s("Hello World!!!");
// convert s to uppercase
for (auto &c : s) // for every char in s (note: c is a reference)
c = toupper(c); // c is a reference, so the assignment changes the char
in s
cout << s << endl;
The output of this code is HELLO WORLD!!!
我还读过:
There is no way to rebind a reference to refer to a different object. Because there is no way to rebind a reference, references must be initialized.
问题:每当引用变量 c
绑定(bind)到字符串 s 的下一个字符时,这段代码不会导致重新绑定(bind)吗?
for (auto &c : s)
c = toupper(c);
最佳答案
没有现有变量的重新绑定(bind),在每次迭代中,“旧”c 死亡,"new"c 再次创建,初始化为下一个字符。 for
循环等同于:
{
auto it = begin(s);
auto e = end(s);
// until C++17: auto it = begin(s), e = end(s);
for(; it!=e; ++it) {
auto &c = *it;
c=toupper((unsigned char)c);
}
}
您可以看到,在每次迭代中,c
都会重新创建并重新初始化。
换句话说,在基于范围的 for
循环的圆括号内声明的变量将循环体作为其作用域。
关于c++ - 使用 C++11 Range for 循环更改字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17321726/