c++ - 使用 C++11 Range for 循环更改字符串中的字符

标签 c++ for-loop c++11 reference

我读入了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/

相关文章:

c++ - Func A 调用 Func B,反之亦然(为什么它不起作用)

java - 在java中编写一个连续的 'for'循环

c++ - std::error_code 的用例

c++ - 当参数是引用时,可变参数模板构造函数选择失败

c++ - 使用BOOST::serialization将二进制存档写入共享内存

c++ - PhysX 地形 - Heightfield 与 TriangleMesh

javascript - 为什么这个循环不输出修改后的 CSS?

c++ - 使用 std::chrono 计算持续时间在需要很长时间时给出 0 纳秒

c++ - 如何使继承的虚函数不可用?

c++ - 如何在LLVM中了解 'nullptr'的源代码?