如何将 std::<list>::reverse_iterator 与运算符 + 一起使用?
how to use std::<list>::reverse_iterator with operator +?
我试过这个:
#include <iterator>
#include <list>
int main()
{
std::list<int> list(200);
std::list<int>::reverse_iterator it = list.rbegin() + 100;
}
在编译时,它抱怨道:
error: no operator "-" matches these operands
operand types are: const std::_List_iterator<int> - std::ptrdiff_t
balabalabalabalabalabalabalabalabalabalabalabala...
我在std::vector
上尝试了相同的代码,它运行得很好。我的问题是如何将std::<list>::reverse_iterator
与operator +
结合使用?
std::list
没有随机访问迭代器。这意味着你不能任意增加它们。您可以使用++
运算符中的任意一个来增加它们:
std::list<int>::reverse_iterator it = list.rbegin()++;
或
std::list<int>::reverse_iterator it = ++(list.rbegin());
您也可以使用std::advance
或std::next
执行多个步骤,但在内部,这些步骤将逐个执行。遍历列表是一种O(N)运算。
例如,
std::list<int>::reverse_iterator it = std::next(list.rbegin(), 100);
或
std::list<int>::reverse_iterator it = list.rbegin();
std::advance(it, 100);
在这两种情况下,++
都将被应用100次。因此,如果您需要经常这样做,那么使用std::vector
而不是std::list
可能会更好,因为这些运算对于向量是O(1)。事实上,您应该有充分的理由使用list
而不是vector
。这很少是一个好的选择。
std::list
有一个双向迭代器。operator +
不是为双向迭代器定义的。它仅为随机访问迭代器定义,例如std::vector
的迭代器。对于双向迭代器,必须使用标准函数std::next
和std::prev
,而对于迭代器所需的次数,则必须使用operator ++
或operator --
。
例如,你可以写
std::list<int>::reverse_iterator it = std::next( list.rbegin(), 100 );
只要该列表具有这样数量的元素。
函数std::next
和std::prev
在标头<iterator>
中声明
一个替代函数是标准函数CCD_ 23。
相关文章:
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 [][] 运算符与向量一起使用?
- 不能将重载比较运算符与 Catch 测试一起使用
- 让类与运算符一起工作更简单的方法
- #define 与运算符一起使用
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- 返回对象如何与分配运算符一起工作
- 将逻辑 OR 与 cout 运算符一起使用
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 我可以将 std:fixed 或 std::setprecision() 与>>运算符一起使用吗?
- 如何使 QList<Type*> 与 indexOf() 和自定义运算符==()一起使用?
- 将 std::forward 与 typeid 运算符一起使用是否有意义
- 如何将 std::<list>::reverse_iterator 与运算符 + 一起使用?
- 与类型转换运算符一起使用时条件运算符"?:"的编译器错误
- 如何将运算符[]与运算符=一起使用
- 与条件运算符一起使用时,动作不一致
- 我可以将enable_if之类的东西与隐式转换运算符一起使用吗
- 如何将运算符+和运算符=一起使用
- C++如何验证输入以与重载>>运算符一起使用
- 如何使用 std::find 与不是 std::less 的<运算符一起使用