将整数作为参数并返回一个数组

Loc*_*ead 1 c++ arrays return

我想创建一个函数,它接受一个整数作为它的参数,并在C++中返回一个数组.这是我想到的伪代码:

function returnarray(integer i)
{
    integer intarr[i];

    for (integer j = 0; j < i; j++) { intarr[j] = j; }

    return intarr;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了将returnarray声明为函数*返回指针的常用方法,但是我不能将整数作为参数.我也不能将j分配给intarr [j].我真的想避免指向一个int,因此我可以使用参数.

有没有办法做到这一点,能够将j分配给intarr [j]而不为它指针?

编辑:

忘了写我想避免矢量.我只有在必须的时候使用它们!(我的理由是我的).

感谢:D

Pup*_*ppy 10

您无法返回堆栈分配的数组 - 它将超出范围并释放内存.此外,C++不允许堆栈分配的可变长度数组.你应该使用std :: vector.

std::vector<int> returnarray(int i) {
    std::vector<int> ret(i);
    for(int j = 0; j < i; j++) ret[j] = j;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

  • @Enabren:除了你可以同时使用矢量速度和安全性. (4认同)

Che*_*Alf 5

你的代码甚至不是有效的c ++,所以我假设你是初学者

使用 std::vector

#include <vector>

std::vector<int> yourFunction( int n )
{
    std::vector<int>  result;
    for( int i = 0;  i < n;  ++i )
    {
        result.push_back( i );
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

免责声明:编码器手中没有触及代码.

干杯&hth.,

  • @MisterSir:使用`std :: vector`将使您的代码更简单,而不是更复杂.首先,不可能有一个返回数组的函数,所以你必须做_something_ else.在几乎每个方面,返回`std :: vector`是最简单的选择. (5认同)
  • @downvoter:请说明您的downvote的原因,以便其他人可以了解答案的错误,或者为什么你的downvote是愚蠢的. (2认同)