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

#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。我无法理解它给出的错误。

最佳答案

在此算法调用中

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

关于c++ - C++添加对列表的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31544840/

10-12 00:27
查看更多