我對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)
在此先感謝您的幫助。
你是對的,我的錯。我從我的代碼複製並粘貼它,並且類型T也是可索引的。這並沒有幫助我指出並且爲併發症感到遺憾。 – thewyliestcoyote
問題是'vector'本身不是一個類型,而是一個模板,你應該聲明它是模板模板參數:'template Container,class T>' – petyanca
你可以提供一個例子嗎?我不知道,我明白了,謝謝 – thewyliestcoyote