C ++ How to set map iterator only for map values

I have several templates that can have either a map or a vector as the main container. I would like the template to expose constant iterators for elements. Most of the information I read about how to set iterators (e.g. this accu article ) uses the form

typedef std::vector<int>::iterator iterator;
typedef std::vector<int>::const_iterator const_iterator;
iterator begin() { return values.begin(); }
iterator end() { return values.end(); }

This really doesn’t work for a template that uses a map, though, since the template can no longer use it it->SomeMemberFunc(), but rather should use it to access the elements it->second.SomeMemberFunc(). Therefore, I am looking to show the iterator on map elements that do not give access to keys, but only to map values.

How to do it?

+4
source share
1 answer

Workaround 1

#include <map>
#include <iterator>

template <typename Iter>
struct map_iterator : public std::iterator<std::bidirectional_iterator_tag,
                      typename Iter::value_type::second_type> 
{
    map_iterator() {}
    map_iterator(Iter j) : i(j) {}
    map_iterator& operator++() { ++i; return *this; }
    map_iterator& operator--() { --i; return *this; }
    bool operator==(map_iterator j) const { return i == j.i; }
    bool operator!=(map_iterator j) const { return !(*this == j); }
    typename map_iterator::reference operator*() { return i->second; }
    typename map_iterator::pointer operator->() { return &i->second; }
    map_iterator operator--(int) { return std::prev(--(*this)); }
    map_iterator operator++(int) { return std::next((++*this)); }
protected:
    Iter i;
};

template <typename Iter>
inline map_iterator<Iter> make_map_iterator(Iter j) {
    return map_iterator<Iter>(j);
}

And then

int main() {
    std::map<int,std::string> m {{1, "Hi"},{2, "Bye"}};

    for (auto i=make_map_iterator(m.begin()); i!=make_map_iterator(m.end());i++)
        cout << *i << endl;
}

Living code.

+2
source

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


All Articles