我发现set这东西很有用.....
它可以去重并且排序,多有用啊!set是用红黑树来维护的,不过这高端的东西我这个蒟蒻还没有学,所以具体原理也不知道。
最常用的set用法:
s.clear()清空。
s.insert(x)将元素x插入一个set中
s.erase(x)删除键值为x的元素
s.find(x)返回键值为x的元素的迭代器
s.begin()和s.end()是返回开头和结尾处的迭代器,set内的元素是已经排好序的,所以s.begin()处的元素是最小的,s.end()已经超出了set的范围,而其前面一个数是set里最大的。
s.lower_bound(x),类似于lower_bound(s.begin(),s.end(),x)操作,但是会快一些(因为set的性质吧)
一道set用法练习题:明明的随机数(这题大家都做过吧....)
#include<iostream> #include<cstdio> #include<cstring> #include<climits> #include<iomanip> #include<set> #include<algorithm> using namespace std; set<int>a; int main() { int i,n,x; scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&x);a.insert(x); } x=a.size(); printf("%d\n",x); for(set<int>::iterator j=a.begin();j!=a.end();j++) printf("%d ",*j); return 0; }