Search code examples
c++sortinguniquestdvector

Can anyone explain how to use unique( ) in the vector?


#include<bits/stdc++.h>
using namespace std;

int main() {
    vector <int> v = {1, 2 , 3, 2 , 1};
    cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
    sort(v.begin(), v.end());
    cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
    unique(v.begin(), v.end());
    cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
}

Output is

1 2 3 2 1
1 1 2 2 3
1 2 3 2 3

I'm not understanding what is unique function and how it is working ??


Solution

  • Aside the fact, that bits/stdc++.h is not the proper header when taking C++ standard into account (please use iostream, vector and algorithm). From: https://en.cppreference.com/w/cpp/algorithm/unique

    Eliminates all except the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

    Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten

    Thus the end of the vector might contain "garbage", but this is fine, as the new end of it is also returned.

    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int main() {
        vector <int> v = {1, 2 , 3, 2 , 1};
        cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
        sort(v.begin(), v.end());
        cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
        auto new_end = unique(v.begin(), v.end());
        auto b = v.begin();
        while (b!=new_end) {
            std::cout << *b++ << " ";
        }
        std::cout << "\n";
        return 0;
    }
    

    demo