【问题标题】:How to declare a c++ function that returns std::list or takes std::list as a parameter type? [closed]如何声明一个返回 std::list 或将 std::list 作为参数类型的 c++ 函数? [关闭]
【发布时间】:2021-08-04 13:07:25
【问题描述】:

我一直在尝试在 C++ 中创建一个函数,它接受一个列表,对其执行一些操作,然后返回它。但该函数不接受 std::list 作为有效的返回类型或参数类型。

#include <iostream>
#include <list>

std::list list_function(int n, std::list progress) {

}

int main() {
    /* std::list<int> test_list = {1, 2, 3, 4, 4854};

    test_list.push_back(10); // some unrelated testing

    for (int x : test_list) {
        std::cout << x << '\n';
    } */
}

我在网上找不到任何答案,我该怎么办?

【问题讨论】:

  • 顺便说一句,最好默认为std::vector容器而不是std::list。

标签: c++ stdlist


【解决方案1】:

std::list 是一个模板库,因此您需要一个模板参数才能将其用作类型。

例如:

#include <list>

std::list<int> list_function(int n, std::list<int> progress) {
    return std::list<int>();
}

int main(void) {
    std::list<int> a = list_function(10, std::list<int>());
    return 0;
}

如果你想创建一个通用函数,你也可以像这样将你的函数模板化:

#include <list>

template<typename T>
std::list<T> list_function(int n, std::list<T> progress) {
    return std::list<T>();
}

int main(void) {
    std::list<int> a = list_function(10, std::list<int>());
    std::list<double> b = list_function(10, std::list<double>());
    return 0;
}

【讨论】:

    【解决方案2】:

    任一模板,

    template <typename T>
    std::list<T> list_function(int n, std::list<T> progress) {
        // ...
    }
    

    或提供固定类型

    std::list<int> list_function(int n, std::list<int> progress) {
        // ...
    }
    

    【讨论】:

    • 非常感谢它的工作原理。
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2013-07-27
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多