2017-04-24 18 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

为了更清楚你想要建立的是一个像数据结构的集合(因为你避免重复)。

另一件来自你的代码是你有大块的内存分配用于这个目的,你只是访问它与arrayPtr和大小。 如果是这种情况您可能正在维护一个MAX_MEMORY_SIZE。 像

#define MAX_MEMORY_SIZE 1000000 

有这种假设,

算法addNumber:

  1. 如果大小+ 1> = MAX_MEMORY_SIZE返回一个 '溢出或最大内存' 例外
  2. 检查对于新元素的存在
  3. 如果找到,则不做任何操作,只需返回
  4. 如果未找到,请复制新元素@ arrayPtr [size](arrayPtr [size] = number)。 (您可以选择让他们在一些秩序,使你的搜索可以有效以及对于您的检查功能,并实现了有所不同。)
  5. 增加大小

算法removeNumber:

  1. 检查给定元素的存在
  2. 如果没有找到,什么也不做,只是返回
  3. 如果找到,循环的所有元素的数组左移1位。像下面的代码。
  4. 减少大小

希望这将带你到一个新的水平。

position = check(arrayPtr, number, size); 
for (i = position; i < size-1; i++) { 
    arrayPtr[i] = arrayPtr[i+1]; 
}