c++删除排序数组中的重复项-打印新数组

标签 c++ algorithm

我正在用 C++ 测试这段代码

#include <iostream>

using namespace std;

int removeDuplicates(int A[], int n) {
    if(n == 0) return 0;

    int index = 0;

    for(int i=0; i<n; i++)
    {
        if(A[index] == A[i])
        {

            continue;
        }
        index++;
        A[index] = A[i];
    }
    cout<<"New array is "<<A[index]<<endl;
    return index+1;
}


int main(){

    int x[10] = {1,1,6};
    int n = 3;
    int z = removeDuplicates(x, n);
    cout<<"Length is "<<z;
}

length的结果是对的。 但是,当 cout 新数组时。结果只有6。 缺少 1 个。

我应该放在哪里cout<<"New array is "<<A[index]<<endl;

给我结果 New array is 16

我需要添加更多代码吗?请帮忙,有人吗?

最佳答案

std::uniquestd::erase 是你的 friend 。

std::vector 也是一个好 friend 。

顺便说一句,您的程序确实正确地删除了重复项;只是输出语句没有显示比单个值 6 更多的数组。

关于c++删除排序数组中的重复项-打印新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775235/

相关文章:

c++ - 在 C++ 中类应该以什么顺序声明?

c++ - OpenCV 和 Eclipse CDT

c# - 算法:分析网页的标签

c++ - 如何旋转树或 AVL 树?

c++ - 如何从 wow64 进程中检索特定内核对象的 64 位地址

c++ - Pow() 真的需要 cmath header 还是 iostream 包含 cmath?

c++ - 通过 xalloc/iword 或通过派生类的 iostream 操纵器?

c++ - 顶点定义框算法中的点?

php - 将中点添加到数组中并在下一次迭代中使用它们

c++ - 对阶乘和多项式的组合进行数值计算