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

Hu *_*ixi 3 c++ iterator

有没有一种方法可以在c ++中生成特定的迭代器?
在c ++中,我只是发现:

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

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

std::string::iterator strIt3 = strHello[3];  // error
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?


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

康桓瑋*_*康桓瑋 7

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

auto it = v.begin();
auto nx = std::next(it, 2);
Run Code Online (Sandbox Code Playgroud)

请注意,n可以为负数:

auto it = v.end();
auto nx = std::next(it, -2);
Run Code Online (Sandbox Code Playgroud)

  • @ Sohil Omer是的,如果* it *是[随机访问迭代器](https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator),可以。 (4认同)