To remove duplicate elements from an array in C++, you can create a program that uses a data structure such as a set to track unique elements or a two-pointer technique to filter duplicates in place.
Here’s an example program that demonstrates how to remove duplicate elements from an array and output the resulting array with unique elements using the two-pointer technique:
#include <iostream>
int removeDuplicates(int arr[], int size) {
// If the array is empty or has only one element, no need to remove duplicates
if (size == 0 || size == 1) {
return size;
}
// Index to store the next unique element
int uniqueIndex = 0;
// Iterate through the array
for (int i = 1; i < size; i++) {
// If the current element is different from the last unique element
if (arr[i] != arr[uniqueIndex]) {
// Move the unique element to the next position
uniqueIndex++;
arr[uniqueIndex] = arr[i];
}
}
// Return the size of the array with unique elements
return uniqueIndex + 1;
}
int main() {
// Define the array
int arr[] = {1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
// Remove duplicates from the array
int newSize = removeDuplicates(arr, size);
// Output the array with unique elements
std::cout << “Array with unique elements: “;
for (int i = 0; i < newSize; i++) {
std::cout << arr[i] << ” “;
}
std::cout << std::endl;
return 0;
}
Here’s how the program works:
- The function removeDuplicates takes an array and its size as parameters.
- If the size of the array is less than 2, there is no need to remove duplicates, so the function simply returns the size.
- The function uses a variable uniqueIndex to keep track of the index where the next unique element should be stored.
- The loop iterates through the array, starting from the second element.
- If an element is different from the element at uniqueIndex, the element is moved to the next position after uniqueIndex.
- uniqueIndex is then incremented to point to the next position for unique elements.
- After the loop completes, the function returns the size of the array with unique elements, which is uniqueIndex + 1.
- In the main function, the array with duplicates removed is printed using the returned size.