【问题标题】:multimap accumulate values多图累积值
【发布时间】:2010-06-24 17:08:46
【问题描述】:

我有一个由

定义的多图
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 函数如何访问第二个迭代器值?

【问题讨论】:

  • 嗨,如果你仍然在迭代它们,为什么不把它添加到你的循环中呢? total_buf_size += it1.second;
  • it1.second 中的“所有值”是什么意思? It1.second 只是一个整数。里面只有价值。
  • @ufotds 有时最简单的步骤就可以解决问题。我用了你提到的total_buf_size += it1.second;。我在尝试使用基于向量容器的 STL 示例的累积时受到影响。我也试图避免循环通过容器。
  • @Rob 我的意思是 it1.second 所指向的所有值的总和

标签: c++ stl multimap accumulate


【解决方案1】:

您的问题在于 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());

【讨论】:

  • 我不明白的是,accumulator 不会用buf_map 而不是buf_map.value_type 调用函数吗?
  • @vivekv80:带有反引号,但我不知道它是否适用于长序列。
  • @ufotds: accumulate 是一种隐藏循环的 STL 算法,您提供的函数一方面必须与您希望返回的类型(累积结果)一起使用,并且通过取消引用产生的类型另一个中的迭代器。
【解决方案2】:

我认为您只需要更改您的 summ 函数以采用地图 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, &amp;summ);

【讨论】:

  • 不起作用,因为初始化程序是 intsumm 在这里没有将 int 作为参数。
  • 我认为它实际上需要接受一个 buf_map,并返回一个临时 buf_map,第二个设置为总和才能工作。见:cplusplus.com/reference/std/numeric/accumulate
【解决方案3】:

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

【讨论】:

  • 这不能解决问题...不过我猜还是谢谢。
【解决方案4】:

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

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

Sgi.com

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多