键盘侠牧师
你的脸上风淡云轻,谁也不知道你的牙咬得有多紧。你走路带着风,谁也不知道你膝盖上仍有曾摔过的伤的淤青。你笑得没心没肺,没人知道你哭起来只能无声落泪。要让人觉得毫不费力,只能背后极其努力。我们没有改变不了的未来,只有不想改变的过去。

set译为集合,是一个内部自动有序且不含重复元素的容器

有时出现需要去掉重复元素的情况

而且有可能因这些元素比较大或者类型不是int型而不能直接开散列表

在这种情况下就可以用set来保留元素本身而不考虑它的个数

但是set提供了更为直观的接口

并且加入set之后可以实现自动排序

头文件是 #include <set>

using namespace std;

 

set中常用的方法


begin()        ,返回set容器的第一个元素

end()      ,返回set容器的最后一个元素

clear()          ,删除set容器中的所有的元素

empty()    ,判断set容器是否为空

max_size()   ,返回set容器可能包含的元素最大个数

size()      ,返回当前set容器中的元素个数

rbegin     ,返回的值和end()相同

rend()     ,返回的值和begin()相 1 #include <iostream> 2 #include <set> 3

 4  using namespace std;
 5  
 6  int main()
 7  {
 8      set<int> s;
 9      s.insert(1);
10      s.insert(2);
11      s.insert(3);
12      s.insert(1);
13      cout<<"set 的 size 值为 :"<<s.size()<<endl;
14      cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;
15      cout<<"set 中的第一个元素是 :"<<*s.begin()<<endl;
16      cout<<"set 中的最后一个元素是:"<<*s.end()<<endl;
17      s.clear();
18      if(s.empty())
19      {
20          cout<<"set 为空 !!!"<<endl;
21      }
22 cout<<"set 的 size 值为 :"<<s.size()<<endl;
     cout<<"set 中 1 出现的次数是 :"<<s.count(1)<<endl;
23 cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl; 24 return 0; 25 }

count() 用来查找set中某个某个键值出现的次数。这个函数在set并不是很实用,因为一个键值在set只可能出现0或1次,这样就变成了判断某一键值是否在set出现过了。

(1)insert()

insert(x)可将x插入set容器中,并自动递增排序和去重

(2)find()

find(value)返回set中对应值为value的迭代器

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<set>
using namespace std;
int main()
{
   set<int> st;
   for(int i=1;i<=3;i++)
   {
     st.insert(i);  
   }
   set<int>::iterator it=find(2);
   printf("%d\n",*it);
    return 0;
}

(3)erase()

①删除单个元素

st.erase(st.find(100));

st.erase(value)

value就是所需要删除的值

②删除一个区间内的所有元素

st.erase(first,last)可以删除一个区间内的所有元素

其中first为所需要删除区间的起始迭代器,而last则为所需要删除区间的末尾迭代器的下一个地址

[first,last)

set<int>::iterator it=st.find(30);

st.erase(it,st.end());

删除元素30至set末尾之间的元素

(4)size()

用来获取set内元素的个数

(5)clear()

用来清空set中的所有元素

 

posted on 2019-11-16 21:48  键盘侠牧师  阅读(252)  评论(0编辑  收藏  举报