首页 > 解决方案 > 如何在 C++ 中生成特定的迭代器

问题描述

有没有办法在 C++ 中生成特定的迭代器?
在 C++ 中,我发现:

std::string strHello = "Hello World";
std::string::iterator strIt = strHello.begin();
std::string::iterator strIt2 = std::find(strHello.begin(), strHello.end(), 'W');

wherestd::find()会返回一个迭代器,.begin()也是迭代器类型。但是如果我想要一个迭代器初始化一个特定的值,比如:

std::string::iterator strIt3 = strHello[3];  // error

我怎样才能做到这一点?


更新:
std::string::iterator strIt3 = strHello.begin() + 3; // works well

标签: c++iterator

解决方案


您可以使用std::next以一般方式返回迭代器的第n个后继:

auto it = v.begin();
auto nx = std::next(it, 2);

注意n可以是负数:

auto it = v.end();
auto nx = std::next(it, -2);

推荐阅读