向量作为c++中递归函数的参数



我想在标题中有一个类似的函数,但当我这样声明时,

void function(vector<int> tab, int n)
{
    if(n > 0)
    {
        tab.push_back(n);
        function(tab, n - 1);
    }
}

它不起作用,因为选项卡仍然是空白的。

您按值获取tab-每个递归调用都将对tab的新副本进行操作。

您将希望通过引用传递tab

void function(std::vector<int>& tab, int n) { ... }

您需要将第一个参数声明为具有类似的引用类型std::vector<int> &

void function( std::vector<int> &tab, int n);

或者,您应该重新定义函数,使其返回一个向量。

这是一个示范节目。

#include <iostream>
#include <vector>
std::vector<int> function( int n )
{
    std::vector<int> v;
    return n > 0 ? v = function( n - 1 ), v.push_back( n ), v : v;
}
int main()
{
    auto v = function( 10 );
    for (auto &item : v)
    {
        std::cout << item << ' ';
    }
    std::cout << 'n';
}

程序输出为

1 2 3 4 5 6 7 8 9 10

如果您想修改在函数范围之外声明的向量,您应该通过引用来传递它

void function(vector<int>& tab, int n)

否则,对function的每次调用都将创建tab的函数本地副本,并且只对该副本进行变异,而不是对原始外部向量进行变异。

最新更新