I have an array a={1,2,3,3,2,2,3,3} and I need to remove the duplicates like this:
1: a={1,2,2,2,3,3}
2: a={1,2,3,3}
3: a={1,2}
I need to remove 2 consecutive duplicates: (1,2,3,3 will be 1,2), (1,2,2,2 will be 1,2).
Here is my try, but as you can see, I need some help.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int a[n];
for (int i = 0; i < n; i++)
std::cin >> a[i];
int i, j;
for (i = 0; i < n; i++)
if (a[i] == a[i + 1]) {
for (j = i + 1; j < n; j++)
a[j - 1] = a[j];
n--;
i--;
}
if (n != 0)
for (int i = 0; i < n; i++)
std::cout << a[i] << " ";
return 0;
}
My problem is that I don't know how to remove 2 consecutive values. After multiple tries, I can't resolve this. Thank you in advance!
3in the last step?std::uniquecombined withstd::remove/std::erase(and maybestd::sort) is what springs to mind.. Definitely no need for all those open-coded loops - std algorithms will do what you need.int a[n]is a non-standard variable length array. It's not supported by c++, though some compilers support it as an extension. Usingint a[n]is not portable.std::uniqueandstd::set, the problem is not to remove all but one duplicates. It's to remove consecutive duplicates pair-wise.