set是STL中一种标准关联容器(vector,list,string,deque都是序列容器,而set,multiset,map,multimap是标准关联容器),它底层使用平衡的搜索树——红黑树实现,插入删除操作时仅仅需要指针操作节点即可完成,不涉及到内存移动和拷贝,所以效率比较高。set,顾名思义是“集合”的意思,在set中元素都是唯一的,而且默认情况下会对元素自动进行升序排列,支持集合的交(set_intersection),差(set_difference) 并(set_union),对称差(set_symmetric_difference) 等一些集合上的操作,如果需要集合中的元素允许重复那么可以使用multiset

  1. #include<set>
  2. #include<iterator>
  3. #include<iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. set<int>eg1;
  8. //插入
  9. eg1.insert();
  10. eg1.insert();
  11. eg1.insert();
  12. eg1.insert();//元素1因为已经存在所以set中不会再次插入1
  13. eg1.insert();
  14. eg1.insert();
  15. //遍历set,可以发现元素是有序的
  16. set<int>::iterator set_iter=eg1.begin();
  17. cout<<"Set named eg1:"<<endl;
  18. for(;set_iter!=eg1.end();set_iter++) cout<<*set_iter<<" ";
  19. cout<<endl;
  20. //使用size()函数可以获得当前元素个数
  21. cout<<"Now there are "<<eg1.size()<<" elements in the set eg1"<<endl;
  22. if(eg1.find()==eg1.end())//find()函数可以查找元素是否存在
  23. cout<<"200 isn't in the set eg1"<<endl;
  24.  
  25. set<int>eg2;
  26. for(int i=;i<;i++)
  27. eg2.insert(i);
  28. cout<<"Set named eg2:"<<endl;
  29. for(set_iter=eg2.begin();set_iter!=eg2.end();set_iter++)
  30. cout<<*set_iter<<" ";
  31. cout<<endl;
  32. //获得两个set的并
  33. set<int>eg3;
  34. cout<<"Union:";
  35. set_union(eg1.begin(),eg1.end(),eg2.begin(),eg2.end(),insert_iterator<set<int> >(eg3,eg3.begin()));//注意第五个参数的形式
  36. copy(eg3.begin(),eg3.end(),ostream_iterator<int>(cout," "));
  37. cout<<endl;
  38. //获得两个set的交,注意进行集合操作之前接收结果的set要调用clear()函数清空一下
  39. eg3.clear();
  40. set_intersection(eg1.begin(),eg1.end(),eg2.begin(),eg2.end(),insert_iterator<set<int> >(eg3,eg3.begin()));
  41. cout<<"Intersection:";
  42. copy(eg3.begin(),eg3.end(),ostream_iterator<int>(cout," "));
  43. cout<<endl;
  44. //获得两个set的差
  45. eg3.clear();
  46. set_difference(eg1.begin(),eg1.end(),eg2.begin(),eg2.end(),insert_iterator<set<int> >(eg3,eg3.begin()));
  47. cout<<"Difference:";
  48. copy(eg3.begin(),eg3.end(),ostream_iterator<int>(cout," "));
  49. cout<<endl;
  50. //获得两个set的对称差,也就是假设两个集合分别为A和B那么对称差为AUB-A∩B
  51. eg3.clear();
  52. set_symmetric_difference(eg1.begin(),eg1.end(),eg2.begin(),eg2.end(),insert_iterator<set<int> >(eg3,eg3.begin()));
  53. copy(eg3.begin(),eg3.end(),ostream_iterator<int>(cout," "));
  54. cout<<endl;
  55.  
  56. return ;
  57. }

set会对元素进行排序,那么问题也就出现了排序的规则是怎样的呢?上面的示例代码我们发现对int型的元素可以自动判断大小顺序,但是对char*就不会自动用strcmp进行判断了,更别说是用户自定义的类型了,事实上set的标准形式是set<Key, Compare, Alloc>,

参数 描述 默认值
Key 集合的关键字和值的类型  
Compare 关键字比较函数,它的参数类型key参数指定的类型,如果第一个参数小于第二个参数则返回true,否则返回false less<Key>
Alloc set的分配器,用于内部内存管理 alloc

下面给出一个关键字类型为char*的示例代码

  1. #include<iostream>
  2. #include<iterator>
  3. #include<set>
  4. using namespace std;
  5. struct ltstr
  6. {
  7. bool operator() (const char* s1, const char* s2) const
  8. {
  9. return strcmp(s1, s2) < ;
  10. }
  11. };
  12.  
  13. int main()
  14. {
  15. const int N = ;
  16. const char* a[N] = {"isomer", "ephemeral", "prosaic",
  17. "nugatory", "artichoke", "serif"};
  18. const char* b[N] = {"flat", "this", "artichoke",
  19. "frigate", "prosaic", "isomer"};
  20.  
  21. set<const char*,ltstr> A(a, a + N);
  22. set<const char*,ltstr> B(b, b + N);
  23. set<const char*,ltstr> C;
  24.  
  25. cout << "Set A: ";
  26. //copy(A.begin(), A.end(), ostream_iterator<const char*>(cout, " "));
  27. set<const char*,ltstr>::iterator itr;
  28. for(itr=A.begin();itr!=A.end();itr++) cout<<*itr<<" ";
  29. cout << endl;
  30. cout << "Set B: ";
  31. copy(B.begin(), B.end(), ostream_iterator<const char*>(cout, " "));
  32. cout << endl;
  33.  
  34. cout << "Union: ";
  35. set_union(A.begin(), A.end(), B.begin(), B.end(),
  36. ostream_iterator<const char*>(cout, " "),
  37. ltstr());
  38. cout << endl;
  39.  
  40. cout << "Intersection: ";
  41. set_intersection(A.begin(), A.end(), B.begin(),B.end(),ostream_iterator<const char*>(cout," "),ltstr());
  42. cout<<endl;
  43. set_difference(A.begin(), A.end(), B.begin(), B.end(),inserter(C, C.begin()),ltstr());
  44. cout << "Set C (difference of A and B): ";
  45. copy(C.begin(), C.end(), ostream_iterator<const char*>(cout, " "));
  46. cout <<endl;
  47. return ;
  48. }

其中的ltstr也可以这样定义

  1. class ltstr
  2. {
  3. public:
  4. bool operator() (const char* s1,const char*s2)const
  5. {
  6. return strcmp(s1,s2)<;
  7. }
  8. };

更加通用的应用方式那就是数据类型也是由用户自定义的类来替代,比较的函数自定义,甚至可以加上二级比较,比如首先按照总分数排序,对于分数相同的按照id排序,下面是示例代码

  1. #include<set>
  2. #include<iostream>
  3. using namespace std;
  4. struct Entity
  5. {
  6. int id;
  7. int score;
  8. string name;
  9. };
  10. struct compare
  11. {
  12. bool operator()(const Entity& e1,const Entity& e2)const {
  13. if(e1.score<e2.score) return true;
  14. else
  15. if(e1.score==e2.score)
  16. if(e1.id<e2.id) return true;
  17.  
  18. return false;
  19. }
  20. };
  21.  
  22. int main()
  23. {
  24. set<Entity,compare>s_test;
  25. Entity a,b,c;
  26. a.id=;a.score=;a.name="bill";
  27. b.id=;b.score=;b.name="mary";
  28. c.id=;c.score=;c.name="jerry";
  29. s_test.insert(a);s_test.insert(b);s_test.insert(c);
  30. set<Entity,compare>::iterator itr;
  31. cout<<"Score List(ordered by score):\n";
  32. for(itr=s_test.begin();itr!=s_test.end();itr++)
  33. cout<<itr->id<<"---"<<itr->name<<"---"<<itr->score<<endl;
  34. return ;
  35. }

(转)C++ STL set() 集合的更多相关文章

  1. STL语法——集合:set 安迪的第一个字典(Andy's First Dictionary,UVa 10815)

    Description Andy, , has a dream - he wants to produce his very own dictionary. This is not an easy t ...

  2. C++ STL Set 集合

    前言 set是STL中的一种关联容器.集合具有无序性,互异性等特点.熟练使用STL中的set模板类,可以比较简单的解决一些编程问题. 关联容器:元素按照关键字来保存和访问,STL中的map,set就是 ...

  3. STL的集合set

    集合: 集合是由元素组成的一个类,其成员可以是一个集合,也可以是一个原子,通常一个元素在一个集合中不能多次出现:由于对实现集合不是很理解,只简单写下已有的STL中的set集合使用: C++中set基本 ...

  4. 【STL】集合运算

    STL中有可以实现交集.并集.差集.对称差集的算法. 使用前需要包含头文件: #include <algorithm> 注:使用计算交集和并集的算法必须保证参与运算的两个集合有序!!! 交 ...

  5. STL&&用法集合

    .....STL是c++里很强势很好用的一系列容器(函数)之类的,之前一直不太会用,所以总是暴毙....想着快比赛了,是时候理一下这些东西了. -1.pair 存放两个基本元素的东西 定义方法: pa ...

  6. C++ STL set集合容器

    汇总了一些set的常用语句,部分参考了这篇:http://blog.163.com/jackie_howe/blog/static/199491347201231691525484/ #include ...

  7. stl的集合set——安迪的第一个字典(摘)

    set就是数学上的集合——每个元素最多只出现一次,和sort一样,自定义类型也可以构造set,但同样必须定义“小于”运算符 以下代码测试set中无重复元素 #include<iostream&g ...

  8. STL set集合用法总结(multiset)

    2017-08-20 15:21:31 writer:pprp set集合容器使用红黑树的平衡二叉树检索树,不会将重复键值插入,检索效率高 logn 检索使用中序遍历,所以可以将元素从小到大排列出来 ...

  9. 单词数 (STL set集合)

    单词数 Problem Description lily的好朋友xiaoou333近期非常空.他想了一件没有什么意义的事情.就是统计一篇文章里不同单词的总数.以下你的任务是帮助xiaoou333解决问 ...

随机推荐

  1. AC日记——Pupils Redistribution Codeforces 779a

    A. Pupils Redistribution time limit per test 1 second memory limit per test 256 megabytes input stan ...

  2. AC日记——[网络流24题]骑士共存 cogs 746

    746. [网络流24题] 骑士共存 ★★☆   输入文件:knight.in   输出文件:knight.out   简单对比时间限制:1 s   内存限制:128 MB 骑士共存问题 «问题描述: ...

  3. Presto查询引擎简单分析

    Hive查询流程分析 各个组件的作用 UI(user interface)(用户接口):提交数据操作的窗口Driver(引擎):负责接收数据操作,实现了会话句柄,并提供基于JDBC / ODBC的ex ...

  4. 洛谷——P2878 [USACO07JAN]保护花朵Protecting the Flowers

    P2878 [USACO07JAN]保护花朵Protecting the Flowers 题目描述 Farmer John went to cut some wood and left N (2 ≤ ...

  5. 洛谷——P1657 选书

    P1657 选书 题目描述 学校放寒假时,信息学奥赛辅导老师有1,2,3……x本书,要分给参加培训的x个人,每人只能选一本书,但是每人有两本喜欢的书.老师事先让每个人将自己喜欢的书填写在一张表上.然后 ...

  6. Codeforces Gym 100203E bits-Equalizer 贪心

    原题链接:http://codeforces.com/gym/100203/attachments/download/1702/statements.pdf 题解 考虑到交换可以减少一次操作,那么可以 ...

  7. JavaSwing仿QQ登录界面,注释完善,适合新手学习

    使用说明: 这是一个java做的仿制QQ登录界面,界面仅使用一个类, JDK版本为jdk-11 素材包的名字为:素材(下载)请在项目中新建一个名字为“素材”的文件夹. 素材: https://pan. ...

  8. Jenkins-------初探

    Jenkins 安装和使用就不说了,说一下jenkins mail的配置,稍微有点坑,记住两个地址一致 插件安装时也出问题,大天朝的防火墙真是醉了,如下 更换我大天朝的镜像站  链接如下     ht ...

  9. iOS -- SKPhysicsJointSpring类

    SKPhysicsJointSpring类 继承自 NSObject 符合 NSCoding(SKPhysicsJoint)NSObject(NSObject) 框架  /System/Library ...

  10. Understand the Business Domain

     Understand the Business Domain Mark Richards EFFECTivE SoFTWARE ARCHiTECTS understand not only tec ...