Group
Arrays and Vectors in C++
Objective
1. Define an array with some duplicate numbers.
2. Implement a function that iterates through the array and removes any duplicates.
3. Store the result in a new array or update the original array to only contain unique elements.
4. Output the new array after removing duplicates.
5. Test the program with different arrays to ensure it works correctly.
Create a program that removes duplicates from an array of numbers.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
#include <unordered_set> // Include unordered_set to easily track unique elements
using namespace std; // Use the standard namespace
// Function to remove duplicates from an array
void removeDuplicates(int arr[], int& size) {
unordered_set<int> uniqueElements; // Declare a set to store unique elements
int index = 0; // Variable to track position in the original array
// Iterate through the array
for (int i = 0; i < size; i++) {
// If the element is not already in the set, add it
if (uniqueElements.find(arr[i]) == uniqueElements.end()) {
arr[index++] = arr[i]; // Assign the unique element to the current index
uniqueElements.insert(arr[i]); // Insert the element into the set
}
}
size = index; // Update the size of the array after removing duplicates
}
int main() {
// Define an array with duplicates
int arr[] = {1, 2, 2, 3, 4, 4, 5, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
// Call the function to remove duplicates
removeDuplicates(arr, size);
// Output the array after removing duplicates
cout << "Array after removing duplicates: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each element of the unique array
}
cout << endl;
return 0; // End of program
}
Output
Array after removing duplicates: 1 2 3 4 5 6