2016-09-20 11 views
-2

resize関数に前のベクトルの要素を含めるにはどうすればよいですか?これは基本的にvectorを模倣しており、私はpush_backpop_backの機能を作成しました。サイズ変更関数に前のベクトルの要素を含めるにはどうすればよいですか?

私はまた、サイズを倍にするresize関数と、サイズの1/2になるresize関数を作成しました。直前のベクトルの要素をサイズ変更されたベクトルに含めることは可能ですか?

私の作成した機能は、resize,push_back,pop_off、およびcopyです。私はresize関数内の以前のベクトル要素をコピーすることができましたが、その他の要素はすべて-192828272のようになりました。したがって、現在は要素をゼロに設定しています。

以下の機能を参照してください。

//1/2 the array size 
template <class T> 
T SimpleVector<T>::resizeDwn(){ 

    // decrease the size 
    arraySize /= 2; 

    // Allocate memory for the array. 
    aptr = new T [arraySize]; 
    if (aptr == 0) 
     memError(); 

    // Set the elements to zero 
    for (int count = 0; count < arraySize; count++){ 
     aptr[count] = 0; 
    } 
    // Return the array 
    return *aptr; 
} 

//Double the array size 
template <class T> 
T SimpleVector<T>::resizeUp(){ 

    // Increase the size 
    arraySize *= 2; 

    // Allocate memory for the array. 
    aptr = new T [arraySize]; 
    if (aptr == 0) 
     memError(); 

    // Set the elements to zero 
    for (int count = 0; count < arraySize; count++){ 
     aptr[count] = 0; 
    } 

    return *aptr; 
} 

Program output

+2

この大規模なファイルをダンプすることが重要だと思うのはなぜですか?あなたの質問はサイズ変更と関連しているだけで、クラスの無関係なすべてのメソッドの詳細を示していますか?あなたはあなたの質問を編集し、無関係なすべてのフィラーを削除し、関連する部分だけを残す必要があります。 –

+0

コンストラクタが例外をスローした場合、なぜプログラムをシャットダウンしていますか( 'memError'関数)? [これを読む](http://stackoverflow.com/questions/22843189/exit-call-inside-a-function-which-should-return-a-reference/22843464#22843464)。代入演算子もありません。 – PaulMcKenzie

+0

あなたのresize()関数に関しては、古い配列をどこで削除するのですか?典型的な 'vector'クラスには、アクセス可能な要素の実際の数と、resize()メソッドを呼び出す前に追加できる要素の最大数を決定する「容量」の2つの「サイズ」があります。あなたのベクトルクラスはこれを欠くので、メモリリークの原因に加えて非常に非効率的です。 – PaulMcKenzie

答えて

0

私はあなたが求めているものを実行しようとしています。これに拘束チェックは追加されていません。

template <class TT> 
class SimpleVector { 
    TT* arr; 
    int size; 
public: 
    SimpleVector() {} 

    SimpleVector(TT n) { 
     this->arr = new TT[n]; 
     this->size = 0; 
    } 

    int getLength() { 
     return this->size; 
    } 

    void resizeUp(SimpleVector old) { // Here I have modified your resizeUp declaration 
     this->size = old.getLength() * 2; 
     this->arr = new TT[pointer]; 
     /** 
     * Previous two lines are allocating the 
     * array with double the size of Old SimpleVector. 
     */ 
     for(int i = 0; i < old.getLength(); i++) 
      this->arr[i] = old.arr[i]; 
    } 
};  

これに質問を付けてください。

関連する問題