multimap累积值

时间:2010-06-24 17:08:46

标签: c++ stl multimap accumulate

我有一个由

定义的多图
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;

}

我想总结it1.second指向的所有值 std :: accumulate函数如何访问第二个迭代器值?

4 个答案:

答案 0 :(得分:2)

你的问题在于summ函数,你实际上需要更好的东西才能处理2种不匹配的类型。

如果你很幸运,这可行:

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

如果你不幸(取决于accumulate的实施方式),你可以随时:

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

然后使用:

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

答案 1 :(得分:1)

我认为您只需更改summ函数即可获取map value_type。这完全没有经过考验,但应该提出这个想法。

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

并称之为:

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

答案 2 :(得分:0)

  

Accumulate是求和的推广:它计算init的总和(或其他二元运算)和[first, last)范围内的所有元素。

     

...结果首先初始化为init。然后,对于i中的每个迭代器[first, last),按照从头到尾的顺序,它由result = result + *i(在第一个版本中)或result = binary_op(result, *i)更新(在第二个版本中) )。

     

Sgi.com

您的尝试既不是第一版也不是第二版,您错过了初始部分

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

答案 3 :(得分:0)

为什么你会对包含对的东西搞乱?这太复杂了,你最终会犯错误。为什么不定义结构?

相关问题