簡體   English   中英

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

[英]How to generate a specific iterator in 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');

其中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; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM