使用指针在功能中的数组中添加/删除元素
Adding/Removing Elements in an Array Inside a Function Using Pointers
我正在尝试解决这个问题。这是针对一个项目,我们的教练需要此标头。我的检查功能正常工作,但是在添加到阵列时添加我们必须使用指针。我的理解是,我们应该将此数组复制到另一个数组并替换指针。例如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> = max_memory_size返回'溢出或max内存'异常
- 检查是否存在新元素
- 如果发现,什么也不做,只是返回
- 如果找不到,请复制新元素 @ arrayptr [size](arrayptr [size] = number(。(您可以选择以某种顺序保留它们,以便您的搜索也可以有效。因为您的检查功能和实施必须不同(
- 增加尺寸
removenumber的算法:
- 检查给定元素的存在
- 如果找不到,什么也不做,只是返回
- 如果发现,请循环所有元素阵列和左移1位置。像下面的代码。
- 减小尺寸
希望这会带您到一个新的水平。
position = check(arrayPtr, number, size);
for (i = position; i < size-1; i++) {
arrayPtr[i] = arrayPtr[i+1];
}
相关文章:
- QNetworkAccessManager 稍后在添加请求时删除
- Eclipse CDT clang 工具链 - 无法从链接器选项中删除 stdlibc++,但可以添加 libc++,E
- 将类型添加到现有模板而不删除 c++17
- 在动态数组中添加/删除C++元素
- 为什么"std::add_pointer"会添加之前删除的"const"?
- 需要左键作为赋值的左操作数?? 在链表中添加Add_End、删除和Delete_Front?
- 查找排序的容器,其中指向元素的指针在添加/删除时不会更改
- 如何向/从矢量添加/删除<unique_ptr>?
- 使用指针在功能中的数组中添加/删除元素
- 如何使用 zlib 在 zip 文件中添加/删除特定文件
- 在迭代地图时向/从地图添加/删除元素是否安全
- 在Windows上添加/删除文件末尾的字节
- 添加/删除具有模板参数的数据成员
- GCC 杂注,用于在源文件中添加/删除编译器选项
- 添加/删除/更新联系人时获得通知
- C++动态库存系统——添加/删除项目
- 如何在C++中动态添加/删除QML属性
- 在c++中的FLTK中在运行时添加/删除小部件
- 支持在JNI c++中添加/删除java对象
- c++悖论,添加/删除头守卫