std::unique
时间: 2023-09-06 18:14:16 浏览: 42
`std::unique` is a standard library function in C++ that removes consecutive duplicate elements from a range in a container. It is defined in the `<algorithm>` header file.
The function takes two iterators as arguments, which specify the range to be operated on. It then returns an iterator pointing to the new end of the container after the duplicates have been removed.
The function does not actually remove any elements from the container, but rather moves the unique elements to the beginning of the range and returns an iterator to the new end of the range. The remaining elements are still present in the container, but their values are unspecified.
Here is an example usage of `std::unique`:
```
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec{1, 1, 2, 2, 2, 3, 4, 5, 5};
auto new_end = std::unique(vec.begin(), vec.end());
vec.erase(new_end, vec.end());
for (auto i : vec) {
std::cout << i << " ";
}
return 0;
}
```
In this example, the vector `vec` contains consecutive duplicates. We use `std::unique` to remove these duplicates, and then erase the remaining elements from the vector using the `erase` function. Finally, we print out the elements of the vector to verify that the duplicates have been removed.