簡體   English   中英

C ++將數組傳遞給函數

[英]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)
//                         ^

這是關於參數傳遞的更一般問題的特例。

您可能需要考慮以下准則:

  1. 如果要將某些內容傳遞給函數以在函數內部對其進行修改 (並使更改對調用者可見),請按引用傳遞& )。

    例如

     // '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; } 
  2. 如果你想傳遞一些便宜的東西(例如一個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; } 
  3. 如果你想傳遞一些不便宜的東西(例如std::stringstd::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(); } 
  4. 在現代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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM