2015-10-19 43 views
0

我對C++中的模板編程有點新意,並且陷入了困境。我試圖編寫一段代碼來循環容器和模板類型T中的元素。我所擁有的顯然是錯誤的,但我認爲應該讓這個想法貫穿始終。循環播放一個容器作爲模板

template <typename Container, typename T > 
Container<T> MyFunction(Container<T> input) 
{ 
    T precedingElement = input[0]; 
    Container<T> output = input;  
    for(int i=1; i<input.size(); i++) 
    { 
     // Do some work on element in the container 
     // Now update precedingElement 
     precedingElement = input[i]; 
    } 
    return output; 
} 

// Example 
vector<float> a = [0, 1, 2, 3, 4, 5 ...]; 
vector<float> b = MyFunction(a); 
// Another example 
list<MyType> c = [object1, object2, ... ]; 
list<MyType> d = MyFunction(c) 

在此先感謝您的幫助。

回答

0

看起來precedingElement更新應該讀precedingElement = input[i](它是元素類型的,而不是一個集合)

+0

你是對的,我的錯。我從我的代碼複製並粘貼它,並且類型T也是可索引的。這並沒有幫助我指出並且爲併發症感到遺憾。 – thewyliestcoyote

+0

問題是'vector'本身不是一個類型,而是一個模板,你應該聲明它是模板模板參數:'template