简体   繁体   中英

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??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM