c++ - 如何从函数返回具有多个值的数组? C++

标签 c++ function

我正在尝试从函数中返回某个数组,该函数在调用时会将值分配给该数组
该函数应如下所示:

int arr[10];
int values[10] = {1,2,3,4,5,6,7,8,9};
for (int i =0; i<10; i++)
{
arr[i] = values[i];
}
如何将此代码转换为函数?
使用命名空间std;

最佳答案

据我所知,您不应该从函数中返回数组……就像以前一样。
相反,我要做的是将数组的名称传递给函数,并使其以所需的任何方式处理内容。在您的情况下,您只是复制它们,这样就可以正常工作:

#include <iostream>
using namespace std;

void copy_array (const int [], int []); //function prototype

int main()
{
    //Your arrays
    int arr[10];
    int values[10] = {1,2,3,4,5,6,7,8,9};

    //Function call
    copy_array(values, arr);

    //Display contents of array
    for(int i =0; i<10; i++){
        cout << arr[i] << " " ;
    } 

    return 0;
}

//Function definition
void copy_array (const int values[], int arr[]){
    
    for (int i =0; i<10; i++){

        arr[i] = values[i];

    } 

}
输出量
1 2 3 4 5 6 7 8 9 0 
另外,您的数组大小应该是一个常量整数变量。

关于c++ - 如何从函数返回具有多个值的数组? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64072751/

相关文章:

python - 更改python中函数的默认参数

R 在函数内使用临时选项设置

c++ - lli: LLVM 错误: 无法选择: X86ISD::WrapperRIP TargetGlobalTLSAddress:i64

c++ - 如何在剪贴板上放置多种格式?

c++ - A类:public virtual B and class A:public B有什么区别

c++ - iPhone编译移植代码问题: variable given same name as typedef'd type failing

python - 是否可以将相同的可选参数传递给多个函数?

c++ - 在变量地址上调用 delete

javascript - 如何在没有 window.onload 包装器的情况下运行函数

c++ - 内联还有用吗?