I have a vector containing few non-adjacent duplicates.
As a simple example, consider:
2 1 6 1 4 6 2 1 1
I am trying to make this
My question is:
Is there any STL algorithm which can remove the non-adjacent duplicates from the vector ? what is its complexity?
The STL options are the ones you mentioned: put the items in a std::set
, or call std::sort
, std::unique
and calling erase()
on the container. Neither of these fulfills your requirement of "removing the non-adjacent duplicates and maintaining the order of elements."
So why doesn't the STL offer some other option? No standard library will offer everything for every user's needs. The STL's design considerations include "be fast enough for nearly all users," "be useful for nearly all users," and "provide exception safety as much as possible" (and "be small enough for the Standards Committee" as the library Stepanov originally wrote was much larger, and Stroustrup axed out something like 2/3 of it).
The simplest solution I can think of would look like this:
// Note: an STL-like method would be templatized and use iterators instead of
// hardcoding std::vector
std::vector stable_unique(const std::vector& input)
{
std::vector result;
result.reserve(input.size());
for (std::vector::iterator itor = input.begin();
itor != input.end();
++itor)
if (std::find(result.begin(), result.end(), *itor) == result.end())
result.push_back(*itor);
return result;
}
This solution should be O(M * N) where M is the number of unique elements and N is the total number of elements.