2015-07-21 96 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函數以接受正確的參數類型。