Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach for wrapping an STL container in a custom iterator?

To illustrate, say I have a custom container than makes use of the STL std::vector internally. If I typedef std::vector<char*>::iterator to my_container::iterator, then dereferencing the iterator will return a char*. However, my custom container should hide its internals, meaning I want a dereferencing to return a char.

How can this be accomplished?

class my_container {
public:

    typedef std::vector<char*> vector;

private:

    vector vec_;

};

UPDATE: char* is an example. It does not mean a C string; the example would be clearer with an int.

Also, I would like to use std::forward_iterator_tag and std::iterator as this seems a more standard/current approach.

like image 831
magnus Avatar asked May 21 '15 11:05

magnus


1 Answers

If you want your own iterator, just start writing it as a nested class. It will need to wrap a std::vector<char*>::iterator, intercepting the usual operations (e.g. ++, *, --), something like:

class iterator
{
  public:
    iterator& operator++() { ++i_; return *this; }
    char& operator*() { return **i_; }
    ...etc...

  private:
    std::vector<char*>::iterator i_;
};

If you try it and get stuck, post your attempt and we'll help you further.

like image 112
Tony Delroy Avatar answered Oct 05 '22 21:10

Tony Delroy