使用指针在功能中的数组中添加/删除元素

Adding/Removing Elements in an Array Inside a Function Using Pointers

本文关键字:添加 删除 元素 数组 指针 功能      更新时间:2023-10-16

我正在尝试解决这个问题。这是针对一个项目,我们的教练需要此标头。我的检查功能正常工作,但是在添加到阵列时添加我们必须使用指针。我的理解是,我们应该将此数组复制到另一个数组并替换指针。例如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) {

}

关于如何继续进行的任何提示或提示或建议!

更清楚您要构建的是类似数据结构的集合(因为您避免了重复(。

代码中的另一件事是,您为此目的分配了大量的内存,而您只需使用ArrayPtr和大小访问它。如果是这种情况,您可能会维护max_memory_size。像

  #define MAX_MEMORY_SIZE 1000000

有这个假设,

addNumber的算法:

  1. 如果大小 1> = max_memory_size返回'溢出或max内存'异常
  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];
}