Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique() algorithm returns clearly non-unique results [duplicate]

Tags:

c++

std

unique

I have been experimenting with C++'s std::unique() algorithm, but the results it returns really confuse me.

I have done a simple function to test it, like so:

#include <algorithm>
#include <vector>
#include <iostream>

int main()
{
    std::vector<int> test;
    for(int i =0; i < 1000; i++)
        test.push_back(rand() % 10);

    std::vector<int>::iterator last = std::unique<std::vector<int>::iterator>(test.begin(), test.end());
    test.erase(last, test.end());

    for(int x : test)
        std::cout << x << "\n";

    std::cout << std::distance(test.begin(), last) << "\n";
}

And somehow it returns 908 numbers, not unique whatsoever. I even tested it with an online compiler just to be sure that it wasn't my broken stdlibc++, but it's the same result.

like image 1000
Stigl Avatar asked Jan 22 '26 16:01

Stigl


1 Answers

std::unique only removes consecutive duplicates.

It operates in O(n) time complexity, so it can not compare every element with every other element.

Try sorting your vector first.

std::vector<int> test;
for(int i =0; i < 1000; i++)
    test.push_back(rand() % 10);

std::sort(test.begin(), test.end());
std::vector<int>::iterator last = std::unique<std::vector<int>::iterator>(test.begin(), test.end());
test.erase(last, test.end());

for(int x : test)
    std::cout << x << "\n";

std::cout << std::distance(test.begin(), last) << "\n";

Output:

0
1
2
3
4
5
6
7
8
9
10
like image 117
Drew Dormann Avatar answered Jan 25 '26 06:01

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!