C++STL中set的使用策略(二)
阿新 • • 發佈:2020-12-01
看一道 PAT 上的題用set完美解決
程式碼
#include <bits/stdc++.h> using namespace std; int main() { int i,j,k,n,x; set<int> s;//定義一個名為s的集合 while(cin>>n) { for(int i = 0;i < n;i++) { cin>>x; if(s.empty())//判斷集合s是否是空集 { s.insert(x);//是的話向集合s插入一個元素x } else { set<int>::iterator it;//定義一個set型的迭代器 it = s.lower_bound(x);//進行二分查詢 if(it == s.end()) { s.insert(x);//插入一個元素x } else { s.erase(it);//刪除指定元素it s.insert(x);//插入一個元素x } } } int t = s.size();//集合s的大小 cout<<t<<endl; } return 0; }
蒜頭君的隨機數
蒜頭君想在學校中請一些同學一起做一項問卷調查,為了確保實驗的客觀性,他先用計算機生成了 n(1≤n≤100) 個 1 到 1000 之間的隨機整數,對於其中重複的數字,只保留一個,把其餘相同的數去掉,不同的數對應著不同的學生的學號。然後再把這些數從小到大排序,按照排好的順序去找同學做調查。
請你協助蒜頭君完成 “去重” 與“排序”的工作。
輸入格式
共兩行,第一行為一個正整數 n。
第二行有 n 個用空格隔開的正整數,為所產生的隨機數。
輸出格式
第一行輸出一個正整數 m,表示不相同的隨機數的個數。第二行輸出 m 個用空格隔開的正整數,為從小到大排好序的不相同的隨機數。
樣例輸入
10
20 40 32 67 40 20 89 300 400 15
樣例輸出
8
15 20 32 40 67 89 300 400
程式碼
#include <bits/stdc++.h> using namespace std; int main() { set<int> q; int n,x; int sum = 0;; cin>>n; while(n--) { cin>>x; q.insert(x); } cout<<q.size()<<endl; set<int>::iterator it; for(it = q.begin();it != q.end();it++) { sum++; if(sum != q.size()) { cout<<*it<<" "; } else { cout<<*it; } } return 0; }