任何人都可以解释如何在向量中使用 unique( ) 吗?

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;
}

输出是

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

我不明白什么是独特的功能以及它是如何工作的??

撇开事实,考虑到 C++ 标准,bits/stdc++.h 不是正确的 header(请使用 iostreamvectoralgorithm ). 来自: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

因此矢量的结尾可能包含“垃圾”,但这没关系,因为它的新结尾也被返回。

#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