need help with a program

hi guys can you help me i`ve made a program that removes "0" from "n" typed numbers now i have to do the same but remove the duplicate here is my program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <new>
#include <fstream>

using namespace std;

int main ()
{
//declaration of variables:
char pause;
int i,counter=0;
int * deranged,* aranged;
ofstream ofs;



cout << "How many numbers would you like to type? ";
cin >> i;
deranged= new (nothrow) int[i];
if (deranged == nullptr)
{
cout << "Error: memory could not be allocated";
}
else
{
//fill deranged array from console
for (int n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> deranged[n];
if( deranged[n] == 0 )
{
//counts number of zero values
++counter;
}
}

//prints saved numbers in deranged array
cout << "You have entered: ";
for (int n=0; n<i; n++)
{
cout << deranged[n] << ", ";
}

cout << endl;
//create new array with size of (deranged array - zero values)
//here we sort numbers(only non-zero values are saved!)
aranged= new (nothrow) int[i-counter];
for (int n=0, v=0; n<i; n++)
{
if(deranged[n] != 0)
{
aranged[v] = deranged[n];
++v;
}
}

cout << endl;

//creating file for writing and appending
ofs.open("save_file.txt", ofstream::out | ofstream::app );

//prints sorted numbers
//and save them
cout << "I have sorted: ";
for (int n=0; n< (i-counter); n++)
{
cout << aranged[n] << ", ";
ofs << aranged[n] << ", ";
}

ofs.close();
//free allocated memory!
delete[] deranged;
delete[] aranged;

}



cout << endl << "Press any key to continue...";
cin >> pause;
return 0;
}
Last edited on
Hi, if you want to remove duplicates from an array then probably the easiest way is creating a new array and copying there the values that you want to keep. The problem is "how large must the new array be?" The answer is N, where N is the number of different values in your original array. So how to count them? Well this could be a bit tricky... An easy way is to sort all of your elements in ascending (or descending) order, so that all the duplicates are one next to the other.

Try it and let us know.

P.S. It would be so much easier with vectors instead of arrays!
Topic archived. No new replies allowed.