原因
最近要進行程設的期末考試了,復習STL的時候看到了sort和unique.
以前用的時候總覺得有些模糊,正好趁復習再鞏固一下.
測驗
#include <bits/stdc++.h>
using namespace std;
void print(int* a,int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main()
{
//想要測驗關于unique以及sort相關的函式
//假定資料為1 1 2 6 5 1 1 4 7 5
int a[]={1,1,2,6,5,1,1,4,7,5};
int n=sizeof(a)/sizeof(int);
print(a,n); //1 1 2 6 5 1 1 4 7 5
int* end=unique(a,a+n); //普通的unique只會去除相鄰的重復項
print(a,end-a); //1 2 6 5 1 4 7 5
sort(a,a+n); //先對資料進行排序 時間復雜度O(nlogn)
print(a,n); //1 1 1 1 2 4 5 5 6 7
int* b=unique(a,a+n); //對排序后的資料進行去重
print(a,b-a); //1 2 4 5 6 7
}
結果分析
如果想要對一組資料進行去重操作
- 如果順序重要,可以直接使用unique函式,回傳一個迭代器或者說指標指向末尾位置.
但是只能做到去除相鄰的重復項. - 如果順序不重要,可以先對資料進行sort排序,然后將排序后的資料進行一個unique去重.
通過回傳的迭代器.
對應使用

上述題目來源于SDUOJ-CSP模測第三場
題解核心代碼
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5;
int n,m;//count of Num and operation
int Nums[maxn];
void init()
{
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>Nums[i];
int* b=unique(Nums,Nums+n);
n=b-Nums;
}
void Operation()
{
int temp,a,b;
cin>>temp;
if(temp==1)//operation 1
{
cin>>a>>b;//a->b
for(int i=0;i<n;i++)
{
if(Nums[i]==a)
Nums[i]=b;
}
int* end=unique(Nums,Nums+n);
n=end-Nums;
}
if(temp==2)
{
cout<<n<<endl;
}
}
int main()
{
init();
for(int i=0;i<m;i++)
Operation();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/287461.html
標籤:其他
上一篇:中綴運算式轉換為后綴運算式
