如何将任何容器的迭代器递增指定值

how to increment the iterator of any container by a specified value?

本文关键字:迭代器 任何容      更新时间:2023-10-16

我在v.begin((+3或v.end((-1等方面遇到错误。为什么我们不能在迭代器上操作?

有两个列表l和m

l.assign(m.begin((+3,m.end((-1(;

这段代码有错误

[Error]与"operator-"不匹配(操作数类型为"std::list::迭代器{aka std::_list_iterator}"answers"int"(

迭代程序尽可能抽象;迭代器可以是一个指向数组的指针,也可以是流中的一个位置,当你递增它时,它会从stdin中读取,任何东西。因此,标准算术运算符仅针对随机访问迭代器实现,因此它们不会将潜在的昂贵操作隐藏在简单语法后面。

为了将任何迭代器递增/递减任意数量,可以使用std::advance:

std::advance(it, 3); //increment by three
std::advance(it, -1); //decrement once

C++11提供了std::nextstd::prev,它们以一种更实用的方式实现这一点:

auto new_it = std::next(it,3); //increment by three
auto new_it = std::prev(it); //decrement once