-10
参照を使用せずに書き込むと、なぜ動作しません。文字列内の文字を取得するときに参照を使用する理由は何ですか?
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;
'char c = s [0]; c = toupper(c); 'ここで' c'は最初に文字列の最初の文字のコピーを保持します。次に、他の値を保持するために再割り当てされます。元の文字列は変更されません。一方、 'char&c = s [0];'と書くと、 'c'は文字列の最初の文字への参照(エイリアス)です。 'c 'への代入は' s [0] 'への代入と同じです。あなたのループでも同じことが起こります。 –
[C++ 11の範囲ベースのループの可能な複製:値または参照への参照でアイテムを取得](https://stackoverflow.com/questions/15176104/c11-range-based-loop-get-item-by-value -or-reference-to-const) –
C++でのより良い方法:[std :: transform](http://en.cppreference.com/w/cpp/algorithm/transform)(この例にはトーパが含まれています) –