范围是如何工作的?

时间:2018-10-11 13:18:08

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

当我对“ range for”语句的工作原理感到困惑时,我正在读它。

下面是一个将字符串转换为大写的程序。

string s("Hello World!!!");

//convert s to uppercase

for( auto &c :s )  // for every char in s
   c= topper(c);   //  c is a reference,so the assignment changes the 
                   //  char in s
cout<< s << endl;

对字符串的引用(即c)如何将元素更改为大写?

我已经搜索了迭代如何在这里工作,但找不到答案。

2 个答案:

答案 0 :(得分:6)

这段代码

for (auto& c : s)
{
    c = toupper(c); 
}

大致翻译为

for (auto it = std::begin(s); it != std::end(s); ++it)
{
    auto& c = *it;
    c = toupper(c);
}

这是基本的迭代器循环,在任何C ++初学者中都涉及到。


cppreference有一个more detailed and precise explanation

答案 1 :(得分:2)

“ c”不是普通变量,它充当字符串中每个元素(字符)的代理(或引用)。

实际上,通过更改“ c”,您实际上是在更改“ c”所指的值。