How to remove duplicate elements from a vector?

Therefore I have std::vector<type>.

The class type does not have operator<, but it does operator==. Thus, I cannot sort my vector using std::unique.

How can I remove duplicate elements from a vector?

+3
source share
1 answer

I think the best option is to write some binary predicate to use to sort the vector and use std::uniquelater. Keep in mind that a predicate must be transitive!

If this is not an option, you can do nothing but use the quartate algorithm:

std::vector<type> a
std::vector<type> result;
for (unsigned i = 0; i < a.size(); ++i) {
  bool repeated = false;
  for (int j = 0; j < i; ++j) {
    if (a[j] == a[i]) {
      repeated = true;
      break;
    }
  }
  if (!repeated) {
    result.push_back(a[i]);
  }
}

// result stores the unique elements.
+1
source

All Articles