multimap accumulate values

家住魔仙堡 提交于 2020-01-06 02:01:08

问题


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.first << " : " << 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?


回答1:


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());



回答2:


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);




回答3:


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?




回答4:


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);


来源:https://stackoverflow.com/questions/3112234/multimap-accumulate-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!