c++ - 如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会改变?

标签 c++ arrays function

using namespace std;
#include<iostream>
int passarr(int b[],int s)
{
   //Some Modification in the array b
    b[0]=0;
    b[s-1]=0;

    //Printing the array b
    for(int i=0;i<s;i++)
    {
        cout<<b[i]<<" ";
    }
    cout<<endl;
}
int main()
{
    int arr[100];
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }

    //Function call and passing array a to the function`
    passarr(arr,n);

    //Printing the array arr
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
}

在这段代码中,我将数组 arr 传递给函数 passarr(),它执行一些修改。问题是修改也会反射(reflect)在原始数组上。有什么方法可以将数组传递给函数,以便在函数中执行任何操作时不会更改原始数组?

最佳答案

Is there any way to pass the array to a function so that the original array does not get changed while performing any operation in the function?

我能想到的选择:

  1. 在函数中复制数组并修改拷贝。保持输入数组不变。

  2. 按值传递 std::vector。对参数的任何更改都不会影响调用函数中的对象。

  3. 如果您在编译时知道数组的大小,请按值传递 std::array。对参数的任何更改都不会影响调用函数中的对象。

关于c++ - 如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101476/

相关文章:

java - 使用 split 将 .txt 文件中的信息存储到数组中

r - 在函数中存储变量

c++ - CPPCheck 在输出中打印无效字符

c++ - 对 STL::抽象数据类型列表进行排序

c++ - 对 C++ 中的基本递归感到困惑

c++ - 检查几个组合框的索引是否唯一

javascript - 当条件和字段名称相同时,如何不允许项目数组中出现重复项?

arrays - 多维数组间接交互

c++ - 重载 C++ 模板类虚函数

c - 将数据发送到 C 中的函数时数据表的更改