![]() |
In C++, vectors are sequence containers that can contain duplicate elements. In this article, we will discuss how to remove all the duplicate elements from a given vector. Example Input: vec = {1,2,3,2,2,1,4,5,6,5,7} Removing Duplicates from a Vector in C++To remove duplicates from the vector, we can use the combination of std::erase and std::unique algorithms. The std::unique moves all the duplicate elements to the end and it returns an iterator pointing to the new end of the current vector. Then we can use the std::erase method to remove all the duplicate elements that are stored at the end of the vector. ExampleThe below example demonstrates the removal of duplicates from a vector using unique and erase methods. C++
Output
1 2 3 7 8 9 11 20 Time Complexity: O(N log N) We can also use set to remove duplicates from vector and unordered_set when the order of the elements do not matter and we want want a solution which is faster. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |