V
V
Vasily Melnikov2018-12-18 17:42:48
C++ / C#
Vasily Melnikov, 2018-12-18 17:42:48

Why is std::unique needed?

The question is not what it does, but why and why is it implemented like that?
Roughly speaking, if there is a data set, then in order to leave only unique elements, you will first have to sort, and then use unique. Otherwise, the behavior is undefined.
Something like this if you didn't mess anything up:

std::vector<int> a = {1, 3, 4, 454, 5454, 4, 3, 2, 2, 1, 1, 2, 3, 5, 2, 1, -32};
std::sort(begin(a), end(a));
a.erase(std::unique(begin(a), end(a)), end(a));

There is a suspicion that this is done, because everyone can have their own sorting already sorted and so on blah blah blah. But it's still weird.
Let's just say once upon a time when I first used this method, I was unpleasantly surprised, because. Naturally man did not read. And just recently I came across a srach about this ...
What are your thoughts?
Maybe he needs something else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Taratin, 2018-12-18
@BacCM

https://ru.cppreference.com/w/cpp/algorithm/unique - it is written nowhere clearer.
To store many unique elements just use std::set or std::unordered_set

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question