从数组中删除多个元素并创建一个动态数组c++
Removing more than one element from an array and creating a dynamic array c++
我对c++还是个新手,所以这对我来说是一个学习过程。我也知道我最初应该使用向量来做这件事,但我有一个指定数组的练习,所以我试图编写一个函数来删除数组中的所有重复元素,但我收到了错误
C2100:非法的间接
如果有人能指引我正确的方向
int main()
{
int *t;
int removel[9] = { 1, 1, 1, 2, 3, 4, 5, 6, 6, };
t = removeAll(removel, 9, 1);
for (int i = 0; i < 8; i++)
cout << t[i] << " ";
}
int* removeAll(int list[], int listlength, int removeitem)
{
int count = 0;
int* list2;
int removeindex;
int length;
int tempindex;
for (int i = 0; i < listlength; i++)
{
if (removeitem == list[i])
count++;
}
length = listlength - (count + 1);
list2 = new int[length];
int j;
while (j<=length)
{
remove_if(list[0], list[listlength - 1], removeitem);
for (j = 0; j < length; j++)
if (list[j] == NULL)// not sure what the remove_if func puts inplace of the removed element
continue;
else
list2[j] = list[j];
}
return list2;
}
首先,应该像计算listlength - count
一样计算length
,而不是计算listlength - (count + 1)
然后,在list2 = new int[length];
之后,您应该复制与removeitem
不同的元素,并跳过其他元素。你可以这样做
int j = 0;
for (int i = 0; i < listlength; i++) {
if (removeitem == list[i])
continue;
list2[j] = list[i];
j++;
}
并返回成功创建的CCD_ 6。但你也应该知道它的大小。您可以通过在main中创建int tSize
并通过链接将其传递给removeAll
来完成此操作。CCD_ 9将其值更改为CCD_。因此,将int & list2size
添加到removeAll
的参数列表中,并在返回list2
之前写入list2size = length;
。最后,打印t
时,将i < 8
更改为i < tSize
。
如果你做了所有这些程序将正常工作,但不要忘记格式化。
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结