2017-05-31 87 views
-5

我有一個列表中有20個數字(theList)。我想backards閱讀並具備此功能來做到這一點:C++返回一個值列表?

template<typename T> 
T funktioner<T>::swap(list<T> &theList) 
{ 
list<T> li; 
auto start = theList.rbegin(), stop = theList.rend(); 
for (auto it = start; it != stop; ++it) 
{ 
    li.push_back(*it); 
} 

return li; 
} 

我調用函數從我的UserInterface在這個函數:

template<typename T> 
void UserInterface<T>::swap() 
{ 
cout << func.swap(List) << endl; 

} 

但是,這並不正常工作,我得到的以下錯誤信息:

error C2440: 'return': cannot convert from 'std::list<T,std::allocator<_Ty>>'to 'int' 
error C2440: 'return': cannot convert from 'std::list<T,std::allocator<_Ty>>'to 'double' 

爲什麼?我不知道我這次做錯了什麼。我認爲我必須創建一個臨時列表並將值返回並返回該列表,但我想我錯了,而且我其實並不擅長。有人能幫我嗎?也許我完全沒有在這裏睡覺? :O

+6

返回類型爲'T',不'名單'。 – LogicStuff

+0

好的,謝謝!我仍然不知道該怎麼做,但我想我必須自己弄清楚,因爲我可以看到我的問題得到了很多負面反應,所以我猜我只是愚蠢。 ( – StudentLerning

+1

)如果你想返回一個T的列表,那麼做*那*而不是返回一個T.此外,整數不是雙。 –

回答

0

在您的代碼中,聲明返回類型T,但您返回的變量的類型爲list<T>。我建議首先使用具體的類型(無模板)開發代碼;之後您可以用佔位符交換具體類型,但具體類型可以更好地瞭解實際發生的情況。 試試下面的代碼,然後把它翻譯成模板:

list<int> swapList(list<int> &theList) 
{ 
    list<int> li; 
    auto start = theList.rbegin(), stop = theList.rend(); 
    for (auto it = start; it != stop; ++it) 
    { 
     li.push_back(*it); 
    } 

    return li; 
} 

int main() 
{ 
    list<int> source { 1,2,3,4 }; 
    list<int> swapped = swapList(source); 
    for (auto i : swapped) { 
     cout << i << " "; 
    } 
}