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

标签 c++ vector

对于这个问题:

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 中的每个字符.外循环导致内循环应用于每个 stringvector<string> .

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

关于c++ - 为什么在 C++ 中需要两个范围 for 循环来更改 vector 的这些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29573203/

相关文章:

C++::使用 vector 迭代器调用类方法?

java - java中的二维 vector 在java中得到模糊的输出

C++电影座位

c++ - 可变类型 vector 的 vector

c++ - 如何编译头文件、实现、驱动文件

c++ - 单继承 C++ 和头文件

c++ - 是否可以将枚举注入(inject)类范围/命名空间?

c++ - C++ 中的简单仿函数,STL

c++ - 在c++中找到两个 vector 中第一个公共(public)条目的位置的最快方法是什么?

c++ - 通过引用传递时的内存使用情况?