c++ - 如何在 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
解决方案
您可以使用std::next以一般方式返回迭代器的第n个后继:
auto it = v.begin();
auto nx = std::next(it, 2);
注意n可以是负数:
auto it = v.end();
auto nx = std::next(it, -2);
推荐阅读
- python - 单击按钮不会更改 kivymd 中的屏幕
- java - 在避免 SQL 注入的同时批量插入到 2 个相关表中
- c++ - 链接器错误 2005/2001 c++,视觉工作室
- java - 谷歌云虚拟机实例不监听外部或内部 IP 地址
- flutter - Flutter:一次多次使用相同的动画小部件
- c++ - 试图在鼠标点读取 GetPixel(),总是返回 4294967 - 有位图和剪切区域
- python - 减去两个包含 datetime.time 的 numpy 数组
- python - TypeError:“set”和“tuple”的实例之间不支持“<”
- java - 如何使 JavaFX 在 mac(Visual Studio Code) 上工作?
- java - 从 Android 应用发送电子邮件时出现问题