jeudi 30 novembre 2017

The base() function of reverse_iterator

From this old question

C++ custom collection reverse_iterator with similar behaviour to std::vector implementation

I thought that the lines (after revising his design a bit)

template <typename Iterator>
class reverse_iterator {
    Iterator _it;
public:
    reverse_iterator(const Iterator& it):_it(it) { }
    Iterator base() const {Iterator it = _it; return --it;}
    typename Iterator::value_type& operator*() const {return *base();}
//  ...
};

were correct (no one replied that they were incorrect). But it doesn't give the same output that this test with std::reverse_iterator gives:

#include <iostream>  
#include <iterator>    
#include <vector>  

int main () {
    std::vector<int> myvector = {1,2,3};
    std::vector<int>::iterator it = std::next(myvector.begin());
    std::reverse_iterator<std::vector<int>::iterator> r(it);
    std::cout << *it << '\n';  // 2
    std::cout << *r << '\n';  // 1
    std::cout << *r.base() << '\n';  // 2
}

which seems to show that the lines should instead be

template <typename Iterator>
class reverse_iterator {
    Iterator _it;
public:
    reverse_iterator(const Iterator& it):_it(it) { }
    Iterator base() const { return _it; }
    typename Iterator::value_type& operator*() const { return *--base(); }
//  ...
};

which would indeed give the same output as with std::reverse_iterator. What is correct here?

Aucun commentaire:

Enregistrer un commentaire