【问题标题】:Adding/Removing Elements in an Array Inside a Function Using Pointers使用指针在函数内的数组中添加/删除元素
【发布时间】:2017-04-24 01:08:55
【问题描述】:

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


}

任何关于如何进行的提示或提示或建议将不胜感激!

【问题讨论】:

    标签: c++ arrays pointers


    【解决方案1】:

    更清楚地说,您要构建的是类似 Set 的数据结构(因为您要避免重复)。

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

      #define MAX_MEMORY_SIZE 1000000
    

    有这个假设,

    addNumber 算法:

    1. 如果 size+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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2018-07-25
      • 2018-11-04
      • 2017-01-30
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      相关资源
      最近更新 更多