【发布时间】:2019-12-27 08:57:36
【问题描述】:
有没有办法在 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::string迭代器是 random access iterators,这意味着strHello.begin() + 3完全有效。 -
@某程序员老兄 哦,是真的,我不知道为什么我第一次尝试时无效。谢谢。
-
@HuXixi 另一方面,
std::string::iterator strIt3 = strHello[3];完全无效,因为operator[]不返回迭代器 -
@HuXixi 如果在您的实际代码中某处使用了
const,您可能会遇到错误。 @robthebloke 的回答涵盖了这一点。