我正在用 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::unique
和 std::erase
是你的 friend 。
std::vector
也是一个好 friend 。
顺便说一句,您的程序确实正确地删除了重复项;只是输出语句没有显示比单个值 6 更多的数组。
关于c++删除排序数组中的重复项-打印新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775235/