简体   繁体   English

begin() vs rbegin() 它们是如何实现的?

[英]begin() vs rbegin() how they are implemented?

In the following image I'm using the same type of iterators which means the same implementation of operator++ so how does the compiler know if it should get the next value or the previous one...?在下图中,我使用了相同类型的迭代器,这意味着 operator++ 的相同实现,那么编译器如何知道它应该获取下一个值还是前一个值......?

在此处输入图像描述

First, the picture you have contains an error.首先,您拥有的图片包含错误。 As you can see here the reverse iterator type of vector is std::reverse_iterator<iterator> which uses the template std::reverse_iterator<T> .正如您在此处看到的,向量的反向迭代器类型是std::reverse_iterator<iterator> ,它使用模板std::reverse_iterator<T> So begin and rbegin have not the same return value (and I also do not think they are convertible to each other).所以beginrbegin的返回值不同(而且我也不认为它们可以相互转换)。

But actually that wouldn't even be a problem, you could implement但实际上这甚至不是问题,你可以实现

struct iter {
    bool reverse;
    pointer ptr;
 
    iter& operator++() {
        if(reverse) --ptr;
        else ++ptr;
        return *this;
     }
};

But type-seperating them is really preferable.但是对它们进行类型分离确实更可取。

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

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