0

I want to get the distinct values of a vector of real numbers and keep their order. For example: [1, -1, 5, -1] -> [1, -1, 5]. What I did so far:

std::vector<double> getDistinctValues(const std::vector<double>& data)
{
    std::unordered_set<double> distinct(data.begin(), data.end());
    std::vector<double> result(distinct.begin(), distinct.end());

    return result;
}

This solution doesn't keep the order.

  • 2
    You might be looking for [`std::unique`](https://en.cppreference.com/w/cpp/algorithm/unique) or `std::unique_copy` – Igor Tandetnik Jan 10 '21 at 18:46
  • When you have a need like this, hunt through a reference to see what pieces of the puzzle the standard library might provide. Do some research! – Asteroids With Wings Jan 10 '21 at 18:59
  • 1
    Are the multiple values in the vector *consecutive* or can they appear in any order (e.g. [1, -1, 5, -1])? The library functions proposed so far require those to be consecutive. – Bob__ Jan 10 '21 at 19:01
  • The repeating values can appear in any order, not only consecutively! – Dragomir Baltov Jan 10 '21 at 19:03

1 Answers1

2

Something along these lines, perhaps:

std::vector<double> sort(const std::vector<double>& data) {
  std::vector<double> result;
  std::unique_copy(data.begin(), data.end(), std::back_inserter(result));
  return result;
}

N.B.: I wouldn't name a function sort when that function's explicit goal is to preserve the order of elements.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • 2
    You could take by value and use `unique` then `erase`. That lets the caller run this on an existing vector without _any_ copies if they want. Yours mandates at least one. – Asteroids With Wings Jan 10 '21 at 18:55
  • 1
    Please note that this solution requires the copies to be consecutive. – Bob__ Jan 10 '21 at 19:12
  • @AsteroidsWithWings I'm not sure I understand. Wouldn't taking a parameter by value require a copy, no matter what happens inside the function? – Igor Tandetnik Jan 10 '21 at 21:23
  • @Bob__ Ah. The example given at the time of writing did have consecutive duplicates. The question was edited after I wrote the answer. However, with non-consecutive duplicates, I'm not sure what "keep their order" means. – Igor Tandetnik Jan 10 '21 at 21:24
  • @IgorTandetnik No, the caller can write `sort(std::move(myVector))`. Your version prohibits making use of move semantics in that way. – Asteroids With Wings Jan 10 '21 at 21:30