Home > Backend Development > C++ > body text

How to Remove Duplicates from an Unsorted Vector while Maintaining Order?

Linda Hamilton
Release: 2024-11-13 05:59:02
Original
379 people have browsed it

How to Remove Duplicates from an Unsorted Vector while Maintaining Order?

Removing Duplicates from an Unsorted Vector

Maintaining the order of first occurrences while eliminating duplicates from an unsorted vector is crucial in various situations. While a straightforward approach utilizing a set and manual iteration is effective, it can be improved upon by leveraging STL algorithms.

To achieve this, the std::copy_if algorithm provides a convenient solution. By defining a predicate that keeps track of elements already processed and returns false for duplicates, we can filter out the desired elements.

If C 11 support is unavailable, the clumsily named std::remove_copy_if can be employed, with its logic inverted. Here's an untested example to illustrate:

template <typename T>
struct NotDuplicate {
  bool operator()(const T& element) {
    return s_.insert(element).second; // true if s_.insert(element);
  }
 private:
  std::set<T> s_;
};
Copy after login

Next, the following code can be used:

std::vector<int> uniqueNumbers;
NotDuplicate<int> pred;
std::copy_if(numbers.begin(), numbers.end(), 
             std::back_inserter(uniqueNumbers),
             std::ref(pred));
Copy after login

In this solution, the std::ref ensures that the stateful functor is not copied internally within the algorithm. However, std::copy_if does not impose any requirements on side-effects of the applied functor.

The above is the detailed content of How to Remove Duplicates from an Unsorted Vector while Maintaining Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template