为什么在 C++ 中需要两个范围 for 循环来更改向量的这些元素?

Why do you need two range for loops to change these elements of a vector in C++?

对于这个问题:

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;
}

我只是想知道为什么你必须在这个块中有两个循环范围:

for (auto &str : vec)
        for (auto &c : str)
          c = toupper(c);

...主动将向量的元素更改为大写,与此相反:

for (auto &str : vec)
      str = toupper(str);

I was just wondering why you have to have two range for loops in this block:

A std::vector<std::string> 类似于 string 的数组。
std::string 类似于字符数组。

当您需要将单词全部转为大写时,您需要将单词的每个字符都转为大写。因此,您需要两个 for 循环。

您可以使用:

str = toupper(str);

如果您使用正确的签名实现 toupper。标准库没有附带一个。标准库自带的toupper版本只能转换一个字符

toupper() 转换单个字符,没有(标准)变体可以转换字符串中的所有字符。

内部循环导致 toupper() 应用于单个 string 中的每个字符。外循环导致内循环应用于 vector<string>.

中的每个 string

综合效果是将向量中每个字符串中的每个字符都转换为大写。

toupper() 需要类型为 char 的参数,因此您不能直接放置 string 进入它,因为没有转换。

现在,

for (auto &str : vec)
      for (auto &c : str)
           c = toupper(c);

我们需要做上面的事情。我可以这样解释:

  1. vec 是一个 vector 因此是一个容器,这个容器的元素是 stringS.
  2. 你可以把string看作是charS的容器。
  3. 现在在代码的最后一部分,我们依次从 字符串 中取出每个字符,并将其转换为 大写 形式。