unique使用案例及原理

发布时间 2023-10-20 17:39:55作者: 一只傲娇璇

使用案例

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iomanip>
#include <ctype.h>
#include <ctime>
#include <stack>
#include <list>
#include <queue>
#include <algorithm>
using namespace std;

int n;
int main()
{
	cin >> n;
	vector<int> a(n);
	for (int i = 0;i<n;i++)
	{
		cin >> a[i];
	}
	sort(a.begin(),a.end());
	unique(a.begin(), a.end());
	int time = a.size();
	for (int i = 0; i < n-1; i++)
	{
		if (a[i] >= a[i + 1])
		{
			time -=time- i-1;
			break;
		}
	}
	cout << time << endl;
	for (int i = 0;i<time;i++)
	{
		cout << a[i] << " ";
	}

	return 0;
}

在使用unique函数时,并不会将重复的数据删除,而是隐藏到容器的最后面,所以我在获取容器的大小时,并没有直接使用a.size()去获取,而是手打