C 返回值列表

C++ return a list of values?

本文关键字:列表 返回值      更新时间:2023-10-16

我有一个列表,其中有20个数字(thelist(。我想阅读它的支持并具有此功能来做到这一点:

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;
}

我在此功能中从我的用户接口调用该函数:

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

在您的代码中,您声明返回类型T,但是您返回的变量具有type 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 << " ";
    }
}