简体   繁体   中英

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.

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 (eg ++ , * , -- ), 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.

The best way? phew!, tough question.

one way is to use the very useful framework that has been created for exactly this purpose by the nice folks at boost.org:

http://www.boost.org/doc/libs/1_58_0/libs/iterator/doc/

Use boost::indirect_iterator .

EDIT: (Untested)

struct S
{
    using iterator =
        boost::indirect_iterator<std::vector<char*>::iterator>;
    using const_iterator =
        boost::indirect_iterator<std::vector<char*>::const_iterator>;

    iterator begin() { return iterator(vec_.begin()); }
    iterator end() { return iterator(vec_.begin()); }
    const_iterator begin() const { return const_iterator(vec_.begin()); }
    const_iterator end() const { return const_iterator(vec_.begin()); }
private:
    std::vector<char*> vec_;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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