Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply std::accumulate algorithm for associative containers?

For a map like std::map, how do I accumulate it's values' sum?
Actually, I made it with a functor and std::for_each algorithm. But I'd also like to make this using std::accumulate algorithm.
I have no idea how to apply it to std::map.
Is this even possible?

struct Accumurator
    : std::unary_function<std::pair<int, int>, void>
{
    Accumurator()
        : totalValue_(0)
    {
    } 

    void operator()(const std::pair<int, int>& p)
    {
        totalValue_ += p.second;
    }

    int result() const
    {
        return totalValue_;
    }

    int totalValue_; 
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::map<int, int> m;
    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 10));
    m.insert(make_pair(3, 10));
    m.insert(make_pair(4, 10));
    m.insert(make_pair(5, 10));
    m.insert(make_pair(6, 10));

    int totalSum = std::for_each(m.begin(), m.end(), Accumurator()).result();

    // How can I apply accumulate algorithm for associative containers.
    // int totalSum = accumulate(m.begin(), m.end(), ???);

    return 0;
}
like image 943
Benjamin Avatar asked Feb 23 '23 09:02

Benjamin


2 Answers

std::accumulate requires an init argument and a binary operation to perform. Your binary operation needs to accept a pair as the second argument and int as the first argument and return int.

struct pair_add {
  int operator()(int i, const std::pair<int, int>& x) {
    return i + x.second;
  }
};
//use as
int totalSum = accumulate(m.begin(), m.end(), 0, pair_add());

The real problem is to get the functor as generic as possible.

like image 32
pmr Avatar answered Apr 07 '23 01:04

pmr


Almost. The functor must be a binary operator taking the return value type as the first and the range type as the second argument:

x = Functor(init, *it++);
x = Functor(x, *it++);
x = Functor(x, *it++);
// ... until it == end

So you don't need a stateful functor at all, a simple function will do:

int map_acc(int lhs, const std::pair<int, int> & rhs)
{
  return lhs + rhs.second;
}

const int sum = std::accumulate(m.begin(), m.end(), 0, map_acc);
like image 130
Kerrek SB Avatar answered Apr 07 '23 03:04

Kerrek SB