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 (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With