I am trying to create a program that will remove all duplicated from an array.
Example, if the input is 1,2,3,2,2,3,4,5, the output should be 1, 2, 3, 4, 5.
#include <iostream>
int RemoveDuplicates( int a[], int n )
{
int k = 0;
for ( int i = 0; i < n; i++ )
{
int j = 0;
while ( j < k && a[j] != a[i] ) j++;
if ( j == k ) a[k++] = a[i];
}
return k;
}
int main()
{
int a[] = { 1, 2, 3, 2, 2, 4, 5 };
std::cout << "The original array:" << std::endl;
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
int k = RemoveDuplicates( a, sizeof( a ) / sizeof( *a ) );
std::cout << "There are " << k << " unique elements" << std::endl;
for ( int i = 0; i < k; i++ ) std::cout << a[i] << ' ';
std::cout << std::endl;
return 0;
}
two thigs and then it works:
- the "k" for cycle must arrive to k<n-1 because inside you compare with "k+1", and you can exit from the array
- "n--" must be putted inside the "if(x== arr[j])"
allright? sorry I can't explain it better, here is the main code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main(){
int arr[] = {1, 2, 1, 1,3, 2, 4}, i, j, k, n = 7 ;
for( i = 0 ; i < n ; i++ ){
for( j = 0 ; j < n && j!=i ; j++ ){
if(arr[i]== arr[j])
{
for( k = j ; k < n-1 ; k++ )
arr[k] = arr[k+1] ;
n--;
}
}
}
for( i = 0 ; i < n ; i++ )
cout<<arr[i]<<" " ;
system("pause");
return 0 ;
}
mingw32-g++.exe -Wall -fexceptions -std=c++11 -std=c++0x -g -c "E:\CODE BLOCKS\qh\main.cpp" -o obj\Debug\main.o
cc1plus.exe: error: unrecognized command line option '-std=c++11'
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings (0 minutes, 0 seconds)
This has nothing common with the code I showed. You should read error messages before report them in panic in the forum. The compiler says that it does not know such option as '-std=c++11'