+ 1

Getting rid of duplicate elements from a vector C++

I wanted to remove all the duplicate elements from a vector so I was searching for an efficient solution for it. I came across a code : sort(number.begin(), numbers.end()); numbers.erase(unique(numbers.begin(),numbers.end()),numbers.end()); Here, "numbers" is the name of a vector. Can you please elaborate the working of this code, I am really not getting the way it is working? Thanks in advance! :)

15th Dec 2018, 5:51 PM
Agnibha Chakraborty
Agnibha Chakraborty - avatar
3 Respuestas
+ 7
Well, to begin with, the vector is sorted using the std::sort() method from the algorithm header (as you might have guessed). Quick reference: http://www.cplusplus.com/reference/algorithm/sort/ To understand the next function call(s), you should move from the inner to the outer one. std::unique() removes all consecutive duplicate values in a range, however, it cannot alter the size of the container. Why is that? Functions from the STL are designed to work with all kinds of containers from the STL, including arrays, which have a fixed size. So because the function cannot alter the size, it replaces duplicate values with the next non-duplicate value and returns an iterator to the last non-duplicate value, which should be considered the new end of the container. All values after that iterator will be duplicates of that last value due to the replacement. Again, quick reference: http://www.cplusplus.com/reference/algorithm/unique/ ...
15th Dec 2018, 6:21 PM
Shadow
Shadow - avatar
+ 7
Continuation: Afterwards, you still have to get rid of all those values at the end, so you erase them starting at the iterator you received from std::unique() until the end of the container. I assume you have some grasp of iterators here, if not, ask away, please. Anyway, you then have a sorted container without any duplicate values left, which you can continue to use for whatever you want.
15th Dec 2018, 6:25 PM
Shadow
Shadow - avatar
+ 4
Very helpful explanation. Thank you so much Shadow.
17th Dec 2018, 6:24 PM
Agnibha Chakraborty
Agnibha Chakraborty - avatar