是否有可能在迭代器上迭代
Is it possible to iterate over an iterator?
我有一个工作程序,使用迭代器将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]);});
}
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?