多重映射累积值

问题描述:

我有多重映射通过多重映射累积值

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 ::累积函数访问第二个迭代器值?

+1

嗨,如果你正在迭代它们,为什么不把它添加到你的循环? 'total_buf_size + = it1.second;' – nus 2010-06-24 17:24:30

+1

您在it1.second中的“所有值”是什么意思? It1.second只是一个int。它只有价值。 – 2010-06-24 17:39:58

+0

@ufotds有时候最简单的一步就是解决问题。我使用了你提到的'total_buf_size + = it1.second;'。我试图使用基于STL示例的向量容器进行累加的方式。另外我试图避免在容器中循环。 – vivekv80 2010-06-24 18:04:41

你的问题是与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()); 
+0

我不明白,'accumulator'不会使用'buf_map'而不是'buf_map.value_type'来调用函数吗? – nus 2010-06-24 17:43:42

+0

ahh代码如何在评论中突出显示?哼。 – vivekv80 2010-06-24 18:15:26

+0

@ vivekv80:反引号,但我不知道它是否适用于长序列。 – 2010-06-25 06:22:58

我想你只需要改变你的summ函数来取代map_type_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);

+0

不起作用,因为初始化程序是一个'int',而'summ'在这里不需要'int'作为参数。 – 2010-06-24 17:31:21

+0

我认为它实际上需要一个buf_map,并且返回一个临时buf_map,第二个被设置为总和才能工作。请参阅:http://www.cplusplus.com/reference/std/numeric/accumulate/ – nus 2010-06-24 17:35:01

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

你为什么招惹含有对对?这太复杂了,你会失败。为什么不定义一个结构?

+1

这不会解决问题...但无论如何,我想。 – 2010-06-24 17:32:56