C++ 确切的范围是如何工作的?
我正在阅读有关“rangeC++ 确切的范围是如何工作的?,c++,c++11,for-loop,reference,C++,C++11,For Loop,Reference,我正在阅读有关“rangefor”语句的内容,但我对它的具体工作原理感到困惑 下面是一个将字符串转换为大写的程序 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 //
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;
字符串s(“你好,世界!!!”);
//将s转换为大写
for(auto&c:s)//对于s中的每个字符
c=顶部(c);//c是一个引用,因此赋值会更改
//s中的字符
不能这段代码
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有一个。c不是一个普通变量,它充当字符串中每个元素(字符)的代理(或引用)
更改“c”实际上就是更改“c”所指的值。c
是char&
而不是std::string&
。您可以找到详细的explanation@FrançoisAndrieux-如果您打算更正OP.related/dupe,请转到答案部分:解释在代码中。如果您不遵守,请告诉我们您不遵守的部分。否则我们注定要重复解释……谢谢维托里奥。我得到了我的答案。@user463035818此时将引用称为“非普通变量”并不不公平level@LightnessRacesinOrbit好吧,二读时我明白了。有时我的写作速度比思考速度快;)