有没有办法创建一个不改变程序中参数的函数
Is there a way to create a function that doesn't change the arrgument in the program
我创建了一个代码。我想在 2 个函数中使用相同的变量,但我不希望函数将值更改为另一个函数。为了让我自己更清楚,这里有一个例子:
int num1(int arr[5][6],int count);
int num2(int arr[5][6],int count2);
int main()
{
int count = 0;
int count2 = 0;
int arr[5][6] = {
{0, 0, 0, 1, 0, 0} ,
{0, 0, 0, 0, 0, 0} ,
{0, 0, 0, 0, 0, 0} ,
{0, 0, 0, 0, 0, 0} ,
{0, 0, 0, 0, 0, 0}
};
cout << num1(arr,count);
cout << num2(arr,count2);
return 0;
}
int num1(int arr[5][6],int count){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
if(arr[i][j] == 1){
count++;
arr[i][j] = 0;
}
}
}
return count;
}
int num2(int arr[5][6],int count2){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
if(arr[i][j] == 1){
count2++;
arr[i][j] = 0;
}
}
}
return count2;
}
此代码将打印 1 和 0,因为 num1 将 arr 中唯一的"1"更改为"0",并且由于 num2 将获得一个所有位置都有 0 的数组。 我想要的是让两个函数都打印 1,这样输出将是"11"
而不是10
。不,在不制作新数组的情况下,我真的很想知道是否有办法用单个数组做到这一点
C数组不像 C++(或 C(中的大多数其他东西那样支持正确的值语义。 正如人们所期望的那样工作的替代方案是std::array
. 要获得 6 宽 x 5 高的阵列,类型为std::array<std::array<int, 6>, 5>
。 由于这有点冗长,您可能需要一个using
语句,例如
using arr_6_5 = std::array<std::array<int, 6>, 5>;
编辑:不幸的是,声明这样的数组有点烦人。 每个数组实际上需要两层大括号:一层用于包装std::array
,另一层用于包装的 C 样式数组(但是,这些间接层在编译过程中被消除(。
const arr_6_5 arr = {{
{{0, 0, 0, 1, 0, 0}} ,
{{0, 0, 0, 0, 0, 0}} ,
{{0, 0, 0, 0, 0, 0}} ,
{{0, 0, 0, 0, 0, 0}} ,
{{0, 0, 0, 0, 0, 0}}
}};
您可以将num1
和num2
的类型签名更改为
int num1(arr_6_5 arr, int count);
int num2(arr_6_5 arr, int count);
如果您确实要编辑原始数组,则它是arr_6_5 & arr
,如果您想读取原始数组而不复制,则arr_6_5 const& arr
。
由于您实际上是将指向 2D 数组的指针传递给函数,因此如果不修改 main 函数中的数组arr
,就无法修改参数arr
。
一种可能的解决方案是将arr
作为const
传递,然后将其复制到临时数组中进行修改。
int num1(const int arr[5][6],int count){
int arrLoc[5][6];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
arrLoc[i][j] = arr[i][j];
if (arrLoc[i][j] == 1) {
count++;
arrLoc[i][j] = 0;
}
}
}
// mutate local copy while leaving `arr` unmodified
mutation(arrLoc);
return count;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何改变c++应用程序的视觉效果
- 有没有办法创建一个不改变程序中参数的函数
- 字符串中的空格是否会改变程序解释它的方式
- 为什么结构数组的内存集会改变程序行为
- 为什么这个程序不会改变任何东西,但它下面的程序却改变了?
- 我如何获得和改变OGRE应用程序的帧率?
- OpenGL在可分离着色器程序中改变不同的位置
- 根据某个字符串改变程序中的一个单词
- 是否有一种方法可以改变MFC SDI应用程序的标题字体?
- 我如何改变另一个程序图标
- 为稍微改变的程序重用稍微改变的Makefile会产生错误
- 添加断点会改变程序的行为
- 根据信号和返回地址改变程序执行流程