对于这个问题:
Read a sequence of words from cin and store the values a vector. After you’ve read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line
这段代码完成了练习:
#include <iostream>
#include <vector>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;
int main()
{
vector<string> vec;
string word;
while (cin >> word)
vec.push_back(word);
for (auto &str : vec)
for (auto &c : str)
c = toupper(c);
for (decltype(vec.size()) i=0; i != vec.size(); ++i)
{
if (i!=0&&i%8 == 0) cout << endl;
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
我只是想知道为什么你必须在这个 block 中有两个循环范围:
for (auto &str : vec)
for (auto &c : str)
c = toupper(c);
...主动将 vector 的元素更改为大写,与此相反:
for (auto &str : vec)
str = toupper(str);
最佳答案
toupper()
转换单个字符,并且没有(标准)变体可以转换字符串中的所有字符。
内部循环导致toupper()
应用于单个 string
中的每个字符.外循环导致内循环应用于每个 string
在vector<string>
.
综合效果是将 vector 中每个字符串中的每个字符都转换为大写。
关于c++ - 为什么在 C++ 中需要两个范围 for 循环来更改 vector 的这些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29573203/