Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C++;_C++ - Fatal编程技术网

C++ 在C++;

C++ 在C++;,c++,C++,我想通过引用用其他值替换数组元素。但我在做这件事的时候遇到了问题。我的代码如下。在下面的代码中,我只得到通过引用传递后的最后一个值10。但是我想得到改变后的值,比如6,7,8,9,10。请建议: #include <iostream> using namespace std; int temp=6; int byreference (int *x){ for (int t=0;t<5;t++){ *x=temp+t; } } int

我想通过引用用其他值替换数组元素。但我在做这件事的时候遇到了问题。我的代码如下。在下面的代码中,我只得到通过引用传递后的最后一个值10。但是我想得到改变后的值,比如6,7,8,9,10。请建议:

#include <iostream>

using namespace std;

 int temp=6;
 int byreference (int *x){
   for (int t=0;t<5;t++){
     *x=temp+t;     
   }
}



int main ()
{   
    int array[5];

    for (int s=0;s<5;s++){
        array[s]=s+1;
        byreference(&array[s]);
        cout<<*&array[s]<<endl;
    }

}
#包括
使用名称空间std;
内部温度=6;
int byreference(int*x){

对于(int t=0;t如果要使用
c++
,那么使用stl类型会更好:

#include <vector>
#include <iostream>
using namespace std;

const int temp=6;
int byreference (std::vector<int> &x){
    for (int t = 0; t<x.size(); t++){
        x[t] = temp + t;  
    }
}

int main ()
{   
    std::vector<int> array(5, 0);

    for (int s = 0; s < array.size(); s++) {
        array[s]=s+1;
        byreference(array);
        cout << array[s] << endl;
    }
}
通过这种方式,您可以避免像在阵列两端运行这样的问题。

这一行

*x=temp+t;  
确保
数组中的所有值都设置为
10

为什么?

temp
设置为
6
,程序中不会更改

在循环中

for (int t=0;t<5;t++)
{
    *x=temp+t;  
}
无矢量:

#include <iostream>

using namespace std;

int temp=6;
int byreference (int *x){
for (int t=0;t<5;t++){
    *(x+t)=temp+t;     
}
}

int main ()
{   
    int array[5];

    for (int s=0;s<5;s++){
        array[s]=s+1;
        byreference (array);
        cout<<array[s]<<endl;
    }

}

如果你使用C++,为什么不使用<代码> STD::vector < /代码>?使用上面的代码,我没有任何问题来创建数组。我所面临的问题是替换值。它只显示函数的最后一个值,这是10。但是我想显示6、7、8、9、10为什么使用循环在代码>引用引用< /代码>?只有最后一次变化才是可见的,无论如何,你应该考虑改变,我的意思是<代码> *&数组[s] <代码>,这是写代码的一种可怕的方法。是的,* * * &只使用数组[s]得到下面的错误:$$ in函数“int ByRebug”(STD::vector & $$):“*X”中的“操作符*”没有匹配
void byreference (int *x)
{
    *x += temp-1;
}
#include <iostream>

using namespace std;

int temp=6;
int byreference (int *x){
for (int t=0;t<5;t++){
    *(x+t)=temp+t;     
}
}

int main ()
{   
    int array[5];

    for (int s=0;s<5;s++){
        array[s]=s+1;
        byreference (array);
        cout<<array[s]<<endl;
    }

}
6
7
8
9
10