从数组中删除多个元素并创建一个动态数组c++

Removing more than one element from an array and creating a dynamic array c++

本文关键字:数组 动态 c++ 一个 删除 元素 创建      更新时间:2023-10-16

我对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

如果你做了所有这些程序将正常工作,但不要忘记格式化。