C++中的unique
时间: 2023-09-13 13:05:33 浏览: 46
`std::unique()`是C++标准库中的一个算法,用于在容器中去除重复元素,保留唯一元素。它的原型如下:
```c++
template<class ForwardIt>
ForwardIt unique(ForwardIt first, ForwardIt last);
```
该函数接受两个迭代器参数,表示容器中需要去除重复元素的范围。它返回一个迭代器,指向不重复元素序列的尾部。
在调用unique()函数之前,需要确保容器中的元素已经按照要求排序。unique()函数会将相邻的重复元素压缩到容器的尾部,并返回指向不重复元素序列的尾部的迭代器。该函数并不会真正地删除容器中的元素,而是返回一个新的逻辑范围(容器中的元素不变,只是迭代器指向的范围发生了变化)。
以下是一个示例,演示如何使用unique()函数:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> vec = {1, 2, 2, 3, 4, 4, 5};
auto last = std::unique(vec.begin(), vec.end());
for (auto it = vec.begin(); it != last; ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
```
可以看到,unique()函数将相邻的重复元素压缩到了容器的尾部,并返回一个指向不重复元素序列的尾部的迭代器。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)