C++ 标准库 <algorithm> 去重函数 unique

本文介绍了C++标准库中的去重函数`unique`,讲解了如何通过该函数对已排序的数组进行相邻元素去重,并提供了不同类型的数组(包括int数组和vector数组)在去重后的删除操作示例,展示了如何利用返回的迭代器高效地完成去重任务。

摘要:C++ algorithm库中的unique函数可以通过数组的初始地址和结束地址对已经排序好的数组元素进行相邻去重。

1.函数导入

 在cpp文件中,头部写入#include<algorithm>以包含algorithm

2.参数说明

函数声明:

iterator unique(iterator it_1,iterator it_2);

  1. it_1:数组的起始地址。
  2. it_2:数组结束地址。
  3. 返回值是一个迭代器(类似指针,int数组直接返回int指针),它指向的是去重后容器中不重复序列的最后一个元素的下一个元素。

去重实例:

 原始数组

1 2 2 3 3 4 4 5

 去重后数组:

1 2 3 4 5 4 4 5

删除去重:
int类型的数组,可以使用返回的指针实现删除去重操作。
vector类型的数组,可以使用erase方法实现删除去重操作。

3.应用实例

  1. int数组相邻去重
#include<iostream>
#include<algorithm>
using namespace std;

int main() {
	int nums[] = { 1,2,2,3,3,4,4,4,5 };

	unique(nums, nums+9);  // 去重

	for (int num : nums) {
		cout << num << ' ';
	}
	cout << endl;

}

输出结果:

1 2 3 4 5 4 4 4 5
  1. int数组删除去重
#include<iostream>
#include<algorithm>
using namespace std;

int main() {
	int nums[] = { 1,2,2,3,3,4,4,4,5 };

	int* end = unique(nums, nums + 9);  // 去重
	int* p= nums;

	while(p!=end) {
		cout << *p << ' ';
		p++;
	}
	cout << endl;

}

输出结果:

1 2 3 4 5 
  1. vector数组删除去重
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int main() {
	vector<int> nums = { 1,2,2,3,3,4,4,4,5 };

	vector<int>::iterator end = unique(nums.begin(), nums.end());  // 去重

	nums.erase(end, nums.end());  // 删除多余的元素

	for (int num : nums) {
		cout << num << ' ';
	}
	cout << endl;

}

输出结果:

1 2 3 4 5 

END

2021.10.7 第一次编辑

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值