2015-07-21 101 views
1

我有一对int的矢量,我想添加每对的所有第一个元素。我写了以下代码C++添加对列表的元素

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

+6

我停止阅读'#define',为什么不使用'typedef'来代替? –

+0

或'使用PII = std :: pair ;'因为它是C++ 11。 – TartanLlama

回答

6

在算法

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<int, int>所以您需要修复您的lambda函数以接受正确的参数类型。