是否有可能在迭代器上迭代

Is it possible to iterate over an iterator?

本文关键字:迭代 迭代器 有可能 是否      更新时间:2023-10-16

我有一个工作程序,使用迭代器将vector中的字符串大写:

vector<string> v7{ 10, "apples" };  
for (auto vIterator= v7.begin(); vIterator!= v7.end(); ++vIterator){
    auto word = *vIterator; //here
    auto charIterator = word.begin(); 
    *charIterator = toupper(*charIterator);
    *vIterator = word; //also here, i guess i could just print `word` instead?
    cout << *vIterator << endl;
}

我的问题是;在循环的第二行@注释中,我不得不将pointer to the iterator保存到另一个string variable中,然后才能迭代它。

像这样在指针上迭代

*vIterator.begin();

似乎不起作用。

这是正确的做法,还是我错过了什么?
我是C语言的新手,类似指针的工具背后的概念很难理解,即使我可以使用它们,在这种情况下,感觉我做错了。

编辑:语法错误(*vIterator).begin();
在迭代它之前,为什么我必须将它保存到另一个变量中,这是没有意义的,干杯。

既然你使用的是c++ 11,看看你的代码使用范围循环会变得多么简单,就像下面的例子:

  std::vector<std::string> v(10, "apples");  
  for(auto &&word : v) {
    word[0] = toupper(word[0]);
  }

现场演示

现在就它所关注的(*vIterator.begin();似乎没有工作。):

  • 点运算符(即.)比解引用运算符(即*)具有更高的优先级。因此,*vIterator.begin()被解释为*(vIterator.begin())。编译器报错,因为vIterator没有成员begin()

  • 把迭代器看作是指针。通过指向对象的指针/迭代器访问对象成员的正确方法是使用箭头操作符(即vIterator->begin())或先对指针/迭代器解引用,然后使用点操作符(即(*vIterator).begin())。

通过使用迭代器,你的代码将变成:

  std::vector<std::string> v(10, "apples");  
  for(auto it(v.begin()), ite(v.end()); it != ite; ++it) {
    *(it->begin()) = toupper(*(it->begin()));
  }

现场演示

*vIterator.begin();的正确写法是(*vIterator).begin();,或者更常见的是vIterator->begin();。还需要注意的是,您还可以直接访问字符串的第一个字符(而不必遍历它),如word[0]

一个简单的STL -ish方法:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<string> v7{ 10, "apples" };  
    for_each(v7.begin(), v7.end(), [](string& word){word[0] = toupper(word[0]);});
}