【问题标题】:C++ adding elements of list of pairsC ++添加对列表的元素
【发布时间】:2015-07-21 16:38:36
【问题描述】:

我有一个成对的 int 向量,我想添加每对的所有第一个元素。我写了以下代码

#include <iostream>
#include <numeric>
#include <vector>
#include <utility>

#define PII pair<int,int>
using namespace std;

int main() {
    vector<pair<int,int>> v;
    v.push_back(PII(1,2));
    v.push_back(PII(3,4));
    v.push_back(PII(5,6));
    cout<<accumulate(v.begin(),v.end(),0,[](auto &a, auto &b){return a.first+b.first;});
    return 0;
}

这里给出错误http://ideone.com/Kf2i7d。 要求的答案是 1+3+5 = 9。我无法理解它给出的错误。

【问题讨论】:

  • 我停止阅读#define,为什么不改用typedef
  • using PII = std::pair&lt;int,int&gt;;,因为它是 c++11。

标签: c++ algorithm vector lambda stl


【解决方案1】:

在这个算法调用中

cout<<accumulate(v.begin(),v.end(),0,[](auto &a, auto &b){return a.first+b.first;});

它的第三个参数初始化为0,因此推导出类型int

它对应于算法的累加器,累加由 lambda 表达式的第二个参数提供的值。

所以你必须写

cout<<accumulate(v.begin(),v.end(),0,[](auto &a, auto &b){return a + b.first;});

对于我来说,我会用long long int 类型的整数字面量来初始化它。例如

cout<<accumulate(v.begin(),v.end(),0ll,[](auto &a, auto &b){return a +b.first;});

【讨论】:

    【解决方案2】:

    std::accumulate 遍历每个元素并使用当前元素和累加器的当前值调用提供的函数。

    累加器的类型为 int,而不是 pair&lt;int, int&gt;,因此您需要修复 lambda 函数以接受正确的参数类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多