如何在 C++ 中生成特定的迭代器

How to generate a specific iterator in c++

本文关键字:迭代器 C++      更新时间:2023-10-16

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

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

其中std::find()将返回一个迭代器,.begin()也是迭代器类型。但是,如果我想初始化一个迭代器,将有一个特定的值,例如:

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

我该怎么做?


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

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

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

请注意,n可以是负数:

auto it = v.end();
auto nx = std::next(it, -2);
void without_const(std::string& strHello)
{
std::string::iterator strIt3 = strHello.begin() + 3;
}
void with_const(const std::string& strHello)
{
std::string::const_iterator strIt3 = strHello.begin() + 3;
}
void with_auto(const std::string& strHello)
{
auto strIt3 = strHello.begin() + 3;
}