开发者

multimap accumulate values

I have a multimap defined by

typedef std::pair<int, int> comp_buf_pair; //pair<comp_t, dij>
typedef std::pair<int, comp_buf_pair> node_buf_pair;
typedef std::multimap<int, comp_buf_pair> buf_map; //key=PE, value = pair<comp_t, dij>
typedef buf_map::iterator It_buf; 
int summ (int x, int y) {return x+y;}


int total_buf_size = 0;
std::cout << "\nUpdated buffer values" << std::endl;
for(It_buf it = bufsz_map.begin(); it!= bufsz_map.end(); ++it)
{
    comp_buf_pair it1 = it->second;
    // max buffer size will be summ(it1.second)
    //total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), &summ); //error??
    std::cout << "Total buffers required for this config = " << total_buf_size << std::endl;
    std::cout << it->first << " : " << it1.fir开发者_运维百科st << " : " << it1.second << std::endl;

}

I would like to sum all the values pointed by it1.second How can the std::accumulate function access the second iterator values?


Your issue is with the summ function, you actually need something better than that to be able to handle 2 mismatched types.

If you're lucky, this could work:

int summ(int x, buf_map::value_type const& v) { return x + v.second; }

If you're unlucky (depending on how accumulate is implemented), you could always:

struct Summer
{
  typedef buf_map::value_type const& s_type;
  int operator()(int x, s_type v) const { return x + v.second.first; }
  int operator()(s_type v, int x) const { return x + v.second.first; }
};

And then use:

int result = std::accumulate(map.begin(), map.end(), 0, Summer());


I think you'll just need to change your summ function to take the map value_type instead. This is totally untested but it should give the idea.

int summ (int x, const buf_map::value_type& y) 
{
    return x + y.second;
}

And call it:

total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), 0, &summ);


Why do you mess about with pairs containing pairs? It is too complicated and you'll wind up making errors. Why not define a struct?


Accumulate is a generalization of summation: it computes the sum (or some other binary operation) of init and all of the elements in the range [first, last).

... The result is first initialized to init. Then, for each iterator i in [first, last), in order from beginning to end, it is updated by result = result + *i (in the first version) or result = binary_op(result, *i) (in the second version).

Sgi.com

Your attempt was neither first or second version, you missed the init part

total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), 0, &summ);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜