![]() |
In C++, vector is a sequential template class, part of STL(Standard Template Library). A vector in C++ is a resizable array because it can change its size either by growing or shrinking when an element is added or removed from the vector, respectively. Hence, it is also called a dynamic array because of its property of growing and shrinking in size as the element is added or removed from it. In this article, we will learn how to erase duplicates and sort a vector in C++. Example: Input: In the example given above, the input my_vector contains 1, 4, and 6 as duplicate elements. So, our main aim would be to remove them from my_vector and modify my_vector such that it contains the unique elements. It means that every element given in the input vector must appear only once in the output of my_vector vector. Ways to Erase Duplicate Elements and Sort a VectorThere are two efficient approaches to erase duplicates and sort the vector in C++: 1. Erase Duplicate Elements and Sort Vector Using std::uniqueIn C++, the std::unique() function is declared in the <algorithm> header. This function transfers all the consecutive duplicate elements in a vector to the end of the vector. We can then use the std::erase() function to remove the duplicate part. In sorted vector, all the duplicate elements are consecutive to each other. Therefore, sorting the vector before using the std::unique will work as we want. We can sort the vector using std::sort(). Syntax of std::unique()unique(first, last); Syntax of std::sort()sort(first, last); Syntax of std::erase()erase(first, last); Example
Output Vector after removing duplicates: 1 3 4 5 6 Time Complexity: O(n logn), where n is the number of elements 2. Erase Duplicate Elements and Sort Vector Using a SetIn C++, sets contain unique elements in some defined order. So, we can place all the elements of the input vector in a set. This will ensure that all the elements in the set have unique occurrences(without duplicate occurrences) and will be in the given order. Then, we can replace all the input vector values with the values inside the set. Example
Output Vector after removing duplicates: 1 3 4 5 6 Time Complexity: O(n logn), where n is the number of elements |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |