Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keys / Values Functionality to Iterators in C++

I know this questions has come up in various guises before, but this is slightly different.

I have a class which contains a std::map. Although I wish to use the map for other purposes inside the class, externally I want to expose an iterator adapter to just the values inside the map (ie the second item in the std::pair).

For example in python I might do something like this:

def __iter__(self):
    return self._dict.itervalues()

How do I go about doing this in c++, hiding the implementation inside the class?

Thanks,

Dan

like image 573
Dan Avatar asked Jan 27 '09 22:01

Dan


People also ask

Which iterators have the same functionality as C language pointers?

Random-Access Iterators: They are the most powerful iterators. They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container. They are the ones whose functionality are same as pointers.

How do iterators work in C?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.


1 Answers

Have a look at Boost's transform_iterator which provides exactly this kind of functionality:

template <typename K, typename V>
struct get_value {
    const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};

class your_class {
    typedef map<int, float> TMap;
    TMap mymap;

public:
    typedef get_value<TMap::key_type, TMap::data_type> F;
    typedef
        boost::transform_iterator<F, TMap::iterator>
        value_iterator;

    value_iterator begin() { return make_transform_iterator(mymap.begin(), F()); }

    value_iterator end() { return make_transform_iterator(mymap.end(), F()); }

    // TODO Same for const versions.
    // Rest of the interface …
};

Now you can iterate over the values, e.g. like this:

your_class c;
// Fill c with some values …
copy(c.begin(), c.end(), ostream_iterator<float>(cout, " "));
like image 63
Konrad Rudolph Avatar answered Sep 22 '22 06:09

Konrad Rudolph