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

Solution 1:

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