简体   繁体   English

C ++反转迭代器

[英]C++ reverse an iterator

Is it possible to reverse an iterator in C++? 是否可以在C ++中反转迭代器?

For instance, a lot of algorithms are designed on the principle that you pass the beginning and ending iterators: 例如,许多算法的设计原则是您传递开始和结束迭代器:

template <typename T>
void func( Iterator begin, Iterator end ){
    ...
}

Now suppose that internally, I need to iterate forward and backward over the container: 现在假设在内部,我需要在容器上向前和向后迭代:

template <typename T>
void func( Iterator begin, Iterator end ){
    // Iterate forward 
    ...
    // Iterate backward
    ...
}

I COULD certainly pass a negative value to std::advance . 我当然可以将负值传递给std::advance But I am wondering if it would instead be possible to just convert the iterators to reverse iterators. 但我想知道是否可以将迭代器转换为反向迭代器。 Is that possible? 那可能吗?

You can just call std::make_reverse_iterator on the arguments to get a reverse view of the range. 您只需在参数上调用std::make_reverse_iterator即可获得范围的反向视图。 The cpp reference page has a demo. cpp参考页面有一个演示。 That is of course assuming reversal is possible. 这当然是假设可以逆转。

No that is not possible in full generality. 不可能完全普遍。 For example, consider a singly-linked list where you can only iterate in one direction (ie it is Forward iterable but not Bidirectional iterable ). 例如,考虑一个单链表,您只能在一个方向上进行迭代(即,它是前向可迭代但不是双向可迭代 )。

A solution in your case would be for the caller of the function to pass reverse iterators. 在您的情况下,解决方案将是函数的调用者传递反向迭代器。

Reference: https://en.cppreference.com/w/cpp/experimental/ranges#Iterators 参考: https//en.cppreference.com/w/cpp/experimental/ranges#Iterators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM