Iterator in C ++

I am trying to create my own translator. This is a university job. I need an iterator in my Translator class.

class Translator { private: map <string,Word> translator; public: class iterator { friend class Translator; private: map<string,Word>::iterator itm; public: iterator operator++(); pair <string,Word> &operator*(); bool operator==(const iterator &it)const; }; }; 

I am trying to overload operator*() ;

This is the code.

 pair <string, Word>& Translator::iterator::operator*() { return (*itm); } 

Error:

invalid initialization of reference of type 'std::pair<std::basic_string<char>, Word>&' from expression of type 'std::pair<const std::basic_string<char>, Word>

+5
source share
2 answers

The keys of the map are constant, therefore the value type is pair<const string, Word> .

Some type aliases can make the code more friendly:

 typedef map <string,Word> map_type; typedef map_type::value_type value_type; value_type &operator*(); 
+9
source

This is more of an addition than the real answer, but if you need a good iterator (STL complient), you will also need to add a few typedefs, for example, specify the type of your iterator (in your case, you have an input iterator). Then you can use your iterator with any stl algorithm, which can be very nice. However, this can be rather cumbersome.

A very good approach is to use acceleration of facade iterators , you just need to rewrite what you need, these are three methods for input-iterator, which indicate how to increase, test if two iterators are equal and are played. Boost then does all the dirty work, and you can use all the stl algorithms with your standard iterators.

Here is an example from the link I gave you:

 # include <boost/iterator/iterator_facade.hpp> # include "node.hpp" class node_iterator : public boost::iterator_facade< node_iterator , node_base , boost::forward_traversal_tag >{ public: node_iterator() : m_node(0) {} explicit node_iterator(node_base* p) : m_node(p) {} private: friend class boost::iterator_core_access; void increment() { m_node = m_node->next(); } bool equal(node_iterator const& other) const { return this->m_node == other.m_node; } node_base& dereference() const { return *m_node; } node_base* m_node; }; 
+1
source

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


All Articles