2017-04-24 3 views
0

この問題を解決しようとしています。これはプロジェクトのためのものであり、講師はこのヘッダーを必要とします。私はチェック関数が正しく動作しているが、配列に追加するときにポインタを使う必要があります。私の理解は、この配列を別の配列にコピーしてポインタを置き換えることです。たとえば、Array1 {1,2,3}をArray2 {1,2,3,4}にコピーし、4を追加して配列を展開します。残念ながら、ベクトルやその他の関数のリサーチがこの作業に適していると私は思っていますが、ポインタとサイズを使って要素のサイズを変更して追加するだけです。ポインタを使用して関数内で配列内の要素を追加/削除する

// returns the index of the element in "arrayPtr" of "size" 
// that corresponds to the element holding "number" 
// if number is not in the array, returns -1 
int check(int *arrayPtr, int number, int size); 

// adds "number" to the array pointed to by "arrayPtr" of "size". 
// if the number is not already there, if "number" is there - no action 
// Note, the size of the array is thus increased. 
void addNumber(int *& arrayPtr, int number, int &size); 

// removes a "number" from the "arrayPtr" of "size". 
// if "number" is not there -- no action 
// note, "size" changes 
void removeNumber(int *& arrayPtr, int number, int &size); 

私はこれまでのところ、これを持っている:進め方について

// returns the index of the element in "arrayPtr" of "size" 
// that corresponds to the element holding "number" 
// if number is not in the array, returns -1 
int check(int *arrayPtr, int number, int size) { 
    for (int i = 0; i < size; i++) { 
     if (arrayPtr[i] == number) { 
      return i; 
     } 
    } 
    return -1; 
} 

// adds "number" to the array pointed to by "arrayPtr" of "size". 
// if the number is not already there, if "number" is there - no action 
// Note, the size of the array is thus increased. 
void addNumber(int *& arrayPtr, int number, int &size) { 
    if (check(arrayPtr, number, size)==-1) { 
//add the element to the end of the array 

    } 
    //did not run if -1 
} 

// removes a "number" from the "arrayPtr" of "size". 
// if "number" is not there -- no action 
// note, "size" changes 
void removeNumber(int *& arrayPtr, int number, int &size) { 


} 

任意のヒントやヒントやアドバイスをいただければ幸いです!

答えて

0

ビルドしようとしているものは、(重複を避けるため)データ構造のようなセットです。

もう1つのコードは、この目的のために割り当てられた大きなメモリのチャンクで、arrayPtrとsizeを使用してアクセスするだけです。 この場合、MAX_MEMORY_SIZEを維持している可能性があります。 addNumberため 何か

#define MAX_MEMORY_SIZE 1000000 

のような、この仮定をお持ちの

アルゴリズム:

  1. サイズ+ 1> = MAX_MEMORY_SIZE 'のオーバーフローや最大メモリ' の例外を返す
  2. チェックする場合新しい要素の存在の場合
  3. 見つかった場合は何もせずに、単に
  4. 見つからない場合は、新しい要素@ arrayPtr [size](arrayPtr [size] = number)をコピーします。 (あなたの検索が同様に有効であることができるように、いくつかのためにそれらを保つために選択することができ、あなたのチェック機能や実装が異なるように持っていることについて。)
  5. サイズremoveNumberため

アルゴリズム増やしますを与えられた要素の存在を

  1. チェック
  2. 見つからない場合は、何もしないし、単に
  3. を返した場合は、ループのすべての要素の配列dシフト1の位置を左に移動します。以下のようなコード。
  4. これは、次のレベルに行くことができますサイズ

希望を減らします。

position = check(arrayPtr, number, size); 
for (i = position; i < size-1; i++) { 
    arrayPtr[i] = arrayPtr[i+1]; 
} 
関連する問題