How do I remove duplicates with std::queue?

In C++, the `std::queue` container does not provide a direct method for removing duplicate elements. However, you can implement a strategy to achieve this by using an auxiliary data structure like `std::set` to keep track of the elements that have already been seen. Below is an example that demonstrates how to remove duplicates from a `std::queue`:

#include #include #include void removeDuplicates(std::queue& q) { std::set seen; std::queue uniqueQueue; while (!q.empty()) { int value = q.front(); q.pop(); // If this value hasn't been seen before, add it to uniqueQueue if (seen.find(value) == seen.end()) { seen.insert(value); uniqueQueue.push(value); } } // Replace the original queue with the unique values q = uniqueQueue; } int main() { std::queue q; q.push(1); q.push(2); q.push(2); q.push(3); q.push(1); removeDuplicates(q); // Display the contents of the unique queue while (!q.empty()) { std::cout << q.front() << " "; q.pop(); } return 0; }

C++ std::queue remove duplicates C++ example queue operations