cesco said:
I have a map container where the key_type is a pointer to a class
If you use a pointer as a key type to an associateive container, you
need to make sure you provide a comparison that's based on the
referent of the pointer. Comparing pointers based on their actual
values is only meaningful when they are pointers into the same
object/array.
and the value_type is an intenger.
I think you mean data_type is an integer. value_type is actually a
std::pair said:
I'd like to apply the STL algorithm partial_sum to the value_type field of
that map but I don't know how to do it. Probably I have to specify a functor
as fourth argument of partial_sum but I don't know how to implement that.
I thought functor at first, too, but that won't work. The initial
value of the sum is set to the value at the beginning of
the input range, which, for a map, is a std:
air.
What you can do, though, is write a wrapper iterator that
returns only the second part of each pair:
#include <iterator>
template <typename It>
class map_value_iterator : public
std::iterator<std::input_iterator_tag,
typename std::iterator_traits<It>::value_type::second_type>
{
public:
map_value_iterator(It it) : it(it) {}
map_value_iterator(const map_value_iterator<It> &mvi)
: it(mvi.it) {}
map_value_iterator &operator++() { ++it; return *this; }
map_value_iterator operator++(int) { It i = it; ++it; return i; }
bool operator==(const map_value_iterator<It> &mvi) const
{ return it == mvi.it; }
bool operator!=(const map_value_iterator<It> &mvi) const
{ return it != mvi.it; }
bool operator==(const It &i) const { return it == i; }
bool operator!=(const It &i) const { return it != i; }
const typename std::iterator_traits<It>::value_type::second_type *
operator->() const { return &it->second; }
const typename std::iterator_traits<It>::value_type::second_type &
operator*() const { return it->second; }
private:
It it;
};
You could then use it like this:
typedef std::map<int,int> IntMap;
typedef std::vector<int> IntVec;
IntMap m;
IntVec v;
m[0] = 1;
m[1] = 2;
m[2] = 4;
map_value_iterator<IntMap::iterator> begin = m.begin();
map_value_iterator<IntMap::iterator> end = m.end();
std:
artial_sum(begin,end,back_inserter(v));