What is the best way to package an STL container in a custom iterator?

To illustrate, let's say I have a custom container, than using STL std::vector internally. If I typedef std::vector<char*>::iterator before my_container::iterator , then dereferencing the iterator will return a char* . However, my custom container should hide its internal functions, i.e. I want the dereference to return a char .

How can I do that?

 class my_container { public: typedef std::vector<char*> vector; private: vector vec_; }; 

UPDATE: char* is an example. This does not mean the string C; the example will be more clear with int .

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

+6
source share
3 answers

If you want your own iterator, just start writing it as a nested class. It will have to wrap 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 and get stuck, send your try and we will help you in the future.

+5
source

better way? phew !, tough question.

one - use a very useful infrastructure created for this purpose by good people on boost.org:

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

+4
source

Use boost::indirect_iterator .

EDIT: (not indexed)

 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_; }; 
+1
source

Source: https://habr.com/ru/post/987660/


All Articles