3

私は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);
}
4

2 に答える 2

2

これは、パラメーターの受け渡しに関するより一般的な質問の特殊なケースです。

次のガイドラインを検討することをお勧めします。

  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. 安価にコピーできるもの(たとえば、 an int、 adoubleなど) を関数に渡して関数内で観察したい場合は、単純に値で渡すことができます。

    例えば

    // '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. コピーするのが安くないもの(たとえば a 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)
于 2013-06-28T16:41:06.597 に答える