【问题标题】:Removing more than one element from an array and creating a dynamic array c++ [closed]从数组中删除多个元素并创建动态数组c ++ [关闭]
【发布时间】:2016-07-31 19:19:56
【问题描述】:

我还是 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;

}

【问题讨论】:

  • #1 不要在需要变量之前声明它们。
  • 使用向量。我看不出您为什么要使用数组。并且数组是固定大小的。
  • 这是我正在使用的教科书的练习,只是想学习如何完成这项任务。
  • 切换到向量后,考虑一下:stackoverflow.com/questions/36384571/…
  • 好的,#2 格式化你的代码,你希望能够阅读它。 #3 j 未初始化。 #4 阅读reference #5 思考算法。

标签: c++ arrays


【解决方案1】:

首先,您应该计算length,如listlength - count,而不是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++;
    }

并返回成功创建list2。但你也应该知道它的大小。您可以通过在 main 中创建 int tSize 并通过链接将其传递给 removeAll 来实现。 removeAll 将其值更改为 length。所以将int &amp; list2size添加到removeAll的参数列表中,并在返回list2之前写入list2size = length;。最后,在打印t时,将i &lt; 8改为i &lt; tSize

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

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2018-06-10
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多