I have a vector array of n elements and I let users to enter n number of integers. Now, I want my array to contain only distinct integers. In other words, I want it to remove all the copies of an integer so that the array is left with only one occurrence of every integer.
If my vector p = {-1, 1, 4, 1, 4, 7, 3, 7, 7}
output should be: p = {-1, 1, 3, 4, 7}
std::sort(p.begin(), p.end());
for (int i=1; p[i] == p[i+1]; i++){
do {
p.erase(p.begin() + i+1);
} while (p[i]==p[i+1]);
}
However I'm not getting a proper output. Can someone suggest some corrections to my code? Or even suggest a better way to code in C++?
What I have tried:
As you can see, I've tried to sort my array so that all the copies of an integer are placed consecutively. Then I'm erasing the immediate next element whenever I see two elements of same value.