[英]C++ Passing array into function
我对C ++比较陌生,并且很难将我的数组传递给一个单独的函数。 抱怨重新问一个毫无疑问已被回答十几次的问题,但我找不到任何与我的代码问题类似的问题。
int main()
{
Array<int> intarray(10);
int grow_size = 0;
intarray[0] = 42;
intarray[1] = 12;
intarray[9] = 88;
intarray.Resize(intarray.Size()+2);
intarray.Insert(10, 6);
addToArray(intarray);
int i = intarray[0];
for (i=0;i<intarray.Size();i++)
cout<<i<<'\t'<<intarray[i]<<endl;
Sleep(5000);
}
void addToArray(Array<int> intarray)
{
int newValue;
int newIndex;
cout<<"What do you want to add to the array?"<<endl;
cin >> newValue;
cout<<"At what point should this value be added?"<<endl;
cin >> newIndex;
intarray.Insert(newValue, newIndex);
}
您正在传递数组的副本 ,因此任何更改都不会影响原始数据。 通过引用代替:
void addToArray(Array<int> &intarray)
// ^
这是关于参数传递的更一般问题的特例。
您可能需要考虑以下准则:
如果要将某些内容传递给函数以在函数内部对其进行修改 (并使更改对调用者可见),请按引用传递 ( &
)。
例如
// 'a' and 'b' are modified inside function's body, // and the modifications should be visible to the caller. // // ---> Pass 'a' and 'b' by reference (&) // void Swap(int& a, int& b) { int temp = a; a = b; b = temp; }
如果你想传递一些便宜的东西(例如一个int
,一个double
等)到一个函数来在函数内部观察它,你可以简单地传递值 。
例如
// 'side' is an input parameter, "observed" by the function. // Moreover, it's cheap to copy, so pass by value. // inline double AreaOfSquare(double side) { return side*side; }
如果你想传递一些不便宜的东西(例如std::string
, std::vector
等)到一个函数来观察函数内部(不修改它),你可以传递const引用 ( const &
)。
例如
// 'data' is an input parameter, "observed" by the function. // It is in general not cheap to copy (the vector can store // hundreds or thousands of values), so pass by const reference. // double AverageOfValues(const std::vector<double> & data) { if (data.empty()) throw std::invalid_argument("Data vector is empty."); double sum = data[0]; for (size_t i = 1; i < data.size(); ++i) sum += data[i]; return sum / data.size(); }
在现代C ++ 11/14中还有一个额外的规则(与移动语义相关):如果你想传递一些便宜的东西来移动并制作它的本地副本 ,那么传递值和std::move
从价值 。
例如
// 'std::vector' is cheap to move, and the function needs a local copy of it. // So: pass by value, and std::move from the value. // std::vector<double> Negate(std::vector<double> v) { std::vector<double> result( std::move(v) ); for (auto & x : result) x *= -1; return result; }
因为在你的addToArray()
函数中你修改了Array<int>
参数,并且你想要对调用者可见的修改 ,你可以应用规则#1,并通过引用传递 ( &
):
void addToArray(Array<int> & intarray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.