Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Updated 3-Oct-16 3:19am

You may use std::unique after std::sort. See the sample code at std::unique -[^].
Share this answer
Kishaan Jeeveswaran 3-Oct-16 9:03am    
That's a cool option. But it doesn't resize the array after removing the copies of the elements right? I need the array's size after removing all the copies!
Um...look at your for loop: the termination condition is when the first non-duplicate is found, not when you run out of comparisons to make.
You need the loop to work with all elements pairs, and an if condition inside the loop to determine if the element should be removed.
Share this answer
Kishaan Jeeveswaran 3-Oct-16 8:55am    
Do you mean that I should type (p[i] != p[i+1]) in the for loop and replace the inner do-while loop with another for loop?
OriginalGriff 3-Oct-16 9:04am    
No, the outer loop need to check if there are still elements left (i.e. i < number of elements) and the inner loop needs to be removed and replaced with an if that removes one element.
Kishaan Jeeveswaran 3-Oct-16 9:07am    
Ok, got it! I'll try it out. Thanks for your time :)
OriginalGriff 3-Oct-16 9:16am    
You're welcome!
Found the solution!

I used
std::sort(p.begin(), p.end());
p.erase( std::unique( p.begin(), p.end() ), p.end() );

And it automatically deleted all the copies and gave me the new array size! Thanks for the suggestion guys! :)
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900