C++ STL set和multiset的使用 hunst_xiehonghao 总结

2023-05-16

C++ STL set和multiset的使用

std::set<int> s;那个s这个对象里面存贮的元素是从小到大排序的,(因为用std::less作为比较工具。)

1,set的含义是集合,它是一个有序的容器,里面的元素都是排序好的,支持插入,删除,查找等操作,就    像一个集合一样。所有的操作的都是严格在logn时间之内完成,效率非常高。 set和multiset的区别是:set插入的元素不能相同,但是multiset可以相同。

   创建 multiset<ss> base;

   删除:如果删除元素a,那么在定义的比较关系下和a相等的所有元素都会被删除

   base.count( a ):set能返回0或者1,multiset是有多少个返回多少个.

   Set和multiset都是引用<set>头文件,复杂度都是logn

2,Set中的元素可以是任意类型的,但是由于需要排序,所以元素必须有一个序,即大小的比较关系,比如    整数可以用<比较.

3,自定义比较函数;

    include<set>

    typedef struct

    { 定义类型 }

    ss(类型名);

    struct cmp

    {

          bool operator()( const int &a, const int &b ) const

             { 定义比较关系<}

    };

    (运算符重载,重载<)

    set<ss> base; ( 创建一个元素类型是ss,名字是base的set )

    注:定义了<,==和>以及>=,<=就都确定了,STL的比较关系都是用<来确定的,所以必须通     过定义< --“严格弱小于”来确定比较关

4,set的基本操作:

begin()         返回指向第一个元素的迭代器

clear()         清除所有元素

count()         返回某个值元素的个数

empty()         如果集合为空,返回true

end()           返回指向最后一个元素的迭代器

equal_range()   返回集合中与给定值相等的上下限的两个迭代器

erase()         删除集合中的元素

find()          返回一个指向被查找到元素的迭代器

get_allocator() 返回集合的分配器

insert()        在集合中插入元素

lower_bound()   返回指向大于(或等于)某值的第一个元素的迭代器

key_comp()      返回一个用于元素间值比较的函数

max_size()      返回集合能容纳的元素的最大限值

rbegin()        返回指向集合中最后一个元素的反向迭代器

rend()          返回指向集合中第一个元素的反向迭代器

size()          集合中元素的数目

swap()          交换两个集合变量

upper_bound()   返回大于某个值元素的迭代器

value_comp()    返回一个用于比较元素间的值的函数

1:

set元素的插入:

#include <iostream>
#include <string>
#include <set>
using namespace std;
void printSet(set<int> s)
{
 set<int>::iterator i;
 for(i=s.begin();i!=s.end();i++)
        printf("%d ",*i);
 cout<<endl;
}
void main()
{
 //创建空的set对象,元素类型为int,
 set<int> s1;
 for (int i = 0; i <5 ; i++)
  s1.insert(i*10);
 printSet(s1);
 cout<<"s1.insert(20).second = "<<endl;;
 if (s1.insert(20).second)//再次插入20   
  cout<<"Insert OK!"<<endl;
 else
  cout<<"Insert Failed!"<<endl;
 cout<<"s1.insert(50).second = "<<endl;
 if (s1.insert(50).second)
 {cout<<"Insert OK!"<<endl; printSet(s1);}
 else
  cout<<"Insert Failed!"<<endl;
 pair<set<int>::iterator, bool> p;
  p = s1.insert(60);
 if (p.second)
 {cout<<"Insert OK!"<<endl; printSet(s1);}
 else
  cout<<"Insert Failed!"<<endl;
}
继续更新中

 

2: set 的  empty  erase   删除特定元素

#include <iostream>
#include <set>
using namespace std;
int main ()
{
  set<int> myset;
  myset.insert(20);
  myset.insert(30);
  myset.insert(10);
  while (!myset.empty())
  {
     cout <<" "<< *myset.begin();
     myset.erase(myset.begin());
  }
  cout << endl;
  return 0;
}


 

//set::find  
#include <iostream>
#include <set>
using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;
  for (int i=1; i<=5; i++) myset.insert(i*10);    // set: 10 20 30 40 50
  it=myset.find(20);
  myset.erase (it);
  myset.erase (myset.find(40));
  myset.erase (30);
  cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); it++)
    cout << " " << *it;
  cout << endl;
  return 0;
}

 lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个大于等于value 的值。  例如,有如下序列:  ia[]={12,15,17,19,20,22,23,26,29,35,40,51};  用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。

iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。

// 6.set::lower_bound/upper_bound
#include <iostream>
#include <set>
using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it,itlow,itup;

  for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90

  itlow=myset.lower_bound (30);                //    >= 
  itup=myset.upper_bound (60);                 //     >             
  printf("%d %d",*itlow,*itup);  //  30 70
  return 0;
}


 

// 7.set::equal_elements
#include <iostream>
#include <set>
using namespace std;

int main ()
{
  set<int> myset;
  pair<set<int>::iterator,set<int>::iterator> ret;

  for (int i=1; i<=5; i++) myset.insert(i*10);   // set: 10 20 30 40 50

  ret = myset.equal_range(30);

  cout << "lower bound points to: " << *ret.first << endl;
  cout << "upper bound points to: " << *ret.second << endl;

  return 0;
} 


//lower bound points to: 30
//upper bound points to: 40


 set结构体的应用

#include<iostream>
#include<set>
using namespace std;
struct haha
{	
	int a,b;	
	char s;	
	friend bool operator<(struct haha a,struct haha b)	
	{	
		return a.s<b.s;		
	}	
};
set<struct haha>element;
int main()
{	
	struct haha a,b,c,d,t;	
	a.a=1; a.s='b';	
	b.a=2; b.s='c';	
	c.a=4; c.s='d';	
	d.a=3; d.s='a';
	element.insert(d);	
	element.insert(b);	
	element.insert(c);	
	element.insert(a);	
	set<struct haha>::iterator it;	
	for(it=element.begin(); it!=element.end();it++)		
		cout<<(*it).a<<" ";	
	cout<<endl;	
	for(it=element.begin(); it!=element.end();it++)		
		cout<<(*it).s<<" ";	
}


集合的并集 交集  差集 等等 

#include<stdio.h>
#include<string>
#include<set>
#include<iostream>
#include <algorithm>//包含
using namespace std;

struct compare//自定义排序方式
{
	bool operator ()(string s1,string s2)
	{
		return s1>s2;
	}///自定义一个仿函数
};
int main()
{
    typedef  set<string,compare>  SET;
	SET s;//建立第一个集合
	s.insert(string("sfdsfd"));
	s.insert(string("apple"));
	s.insert(string("english"));
	s.insert(string("dstd"));
	cout<<"第一个集合s1为:"<<endl;
	 set<string,compare>::iterator it = s.begin();
	while(it!=s.end())
		cout<<*it++<<"   ";

	SET s2;//建立第二个集合
	s2.insert(string("abc"));
	s2.insert(string("apple"));
	s2.insert(string("english"));
	cout<<endl<<"第一个集合s2为:"<<endl;
	it = s2.begin();
	while(it!=s2.end())
		cout<<*it++<<"   ";
	cout<<endl<<endl;
	
	string str[10];
	string *end =set_intersection(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//求交集,返回值指向str最后一个元素的尾端
	/*set_intersection包含于#include <algorithm>   头文件中  其中上面的不一定非要为set容器 也可以使数组 但是前提是要把2个数组都排好序才可以
	返回值是一个指向交集序列末尾的迭代器 至于是什么迭代器与第5个参数有关 如果是数组 返回为int的迭代器 */
	cout<<"s1,s2的交集为:"<<endl;
	string *first = str;
	while(first<end)
		cout <<*first++<<" ";


	cout<<endl<<endl<<"s1,s2的并集为:"<<endl;
	end =set_union(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//并集
	first = str;
	while(first<end)
		cout <<*first++<<" ";


	cout<<endl<<endl<<"s2相对于s1的差集:"<<endl; 
	first = str;
	end = std::set_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//s2相对于s1的差集
	while(first<end)
		cout <<*first++<<" ";


	cout<<endl<<endl<<"s1相对于s2的差集:"<<endl; 
	first = str;
	end = std::set_difference(s2.begin(),s2.end(),s.begin(),s.end(),str,compare());//s1相对于s2的差集
	
	while(first<end)
		cout <<*first++<<" ";
	cout<<endl<<endl;
	first = str;
	end = std::set_symmetric_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//上面两个差集的并集
	while(first<end)
		cout <<*first++<<" ";
	cout<<endl; 

/*
set<int>   s3   ;   
set<int>::iterator   iter   =   s3.begin()   ;   
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),inserter(s3,iter));   
copy(s3.begin(),s3.end(),   ostream_iterator<int>(cout,"   "));
*/
}

另外一个实例

/*set_intersection()算法计算两个集合[start1, end1)和[start2, end2)的交集, 交集被储存在result中.

两个集合以序列的形式给出, 并且必须先按升序排好位置.

set_intersection()的返回值是一个指向交集序列末尾的迭代器.

set_intersection()以线性时间(linear time)运行.

如果严格弱排序函数对象cmp未指定, set_intersection()将使用<操作符比较元素.

范例
*/

// set_intersection example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  vector<int> v(10);                           // 0  0  0  0  0  0  0  0  0  0
  vector<int>::iterator it;
 
  sort (first,first+5);     //  5 10 15 20 25
  sort (second,second+5);   // 10 20 30 40 50
 
  it=set_intersection (first, first+5, second, second+5, v.begin());
                                               // 10 20 0  0  0  0  0  0  0  0
 
  cout << "intersection has " << int(it - v.begin()) << " elements.\n";
 
  return 0;
}
/*输出: intersection has 2 elements*/






 multiset的删除  重要

a.erase(x);//删除集合中所有的x
multiset<int>::iterator it = a.find(x);
if (it != a.end()) 
{
    a.erase(it);  //这里是删除其中的一个x;  删除的是一个位置  而arase是删除所有位置
}


 

 

 

 

 

 

 

 

 

 

 

 

 

 部分参考地址:


http://www.cnblogs.com/agpro/archive/2010/06/23/1763536.html

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ STL set和multiset的使用 hunst_xiehonghao 总结 的相关文章

随机推荐

  • 如何在IDEA创建一个Servlet项目

    本人菜鸟一枚 xff0c 最近在学习Servlet xff0c 一时兴起 xff0c 就想要写一下新建一个Servlet项目 xff0c 看看能不能帮助到一些有需要的和我一样也是新手的人 1 下载并打开IDEA 下载IDEA xff0c 官
  • 车辆视频检测器检测参数配置

    车辆视频检测器检测参数的最佳配置 span class token class name span class token keyword double span span whiteCarYuZhi span class token op
  • VUE v-for中获取二维对象数组

    对象数组如下 xff1a 34 index 34 34 2 34 34 text 34 34 办公平台 34 34 submenu 34 34 index 34 34 2 1 34 34 text 34 34 企业内部消息 34 34 in
  • c++基础知识第十天:结构体嵌套结构体,结构体作函数参数

    一 结构体嵌套结构体 结构体内的成员可以是另一个结构体 xff08 访问时用 访问到不能访问为止 xff09 1 例如 xff1a 每个老师指导一个学员 xff0c 一个老师的结构体中嵌套一个学生的结构体 include lt iostre
  • ros出现 datatype/md5sum错误

    1 错误图 2 我是在windows用的vs code ssh 另外一台电脑ubuntu18 04系统 xff0c 然后在那边terminal输入rqt plot但是图里面一直空白 xff0c windows这边输出上图报错 一直以为是自己
  • 安卓Android多阶段进度条progress bar附带动画效果

    还在为美工设计出的进度条而发愁吗 xff1f 大家先看效果吧 欢迎加安卓开发交流群 xff1a 308372687 xff08 博主尽可能帮助大家 xff09 转载请注明来源 代码连接 GitHub xff1a https github c
  • 【docker】Docker安装

    版本说明 OS xff1a Centos7 6 x64 Linux内核 3 10 0 1062 12 1 el7 x86 64 Docker Docker version 19 03 14 Docker要求CentOS系统的内核版本高于3
  • Python如何在函数内部使用全局变量

    使用方法 Python在函数内部使用全局变量的一种常用方法如下 xff1a 即首先需在函数外部给一个变量赋初值 xff0c 然后在函数内部用关键字 global 将此变量声明为全局变量 而且 xff0c 不能有形如 global a 61
  • 树莓派3B SWAP空间不足

    在对树莓派3B进行ROS indigo安装时 xff0c 到编译ROS程序这一步时 xff0c 总是失败 xff0c 查看了原因发现 xff0c 在为树莓派安装系统时swap空间没有设置 不过为时未晚 xff0c 现在也可以对swap空间进
  • TX2核心板安装OpenCV3.2(在cuda9.0的环境下)

    今天新到的TX2 xff0c 还有点烫手 xff0c 买来要用在无人机上做视觉的目标识别 xff0c 所以自然要装上OpenCV喽 xff01 TX2核心板买来就自带了cuda9 0 xff0c 据说这个和opencv3不太搭 xff0c
  • c语言面试题 指针30个常错题型

    1 char const p char const p const char p 上述三个有什么区别 xff1f char const p 常量指针 xff0c p的值不可以修改 char const p xff1b 指向常量的指针 xff
  • c++ 笔试面试题 难题精选 持续更新

    第一题 问下面的输出结果是 什么 xff1f include lt stdio h gt include lt iostream gt using namespace std class A protected int m data pub
  • VS2010 添加OnInitDialog的方法

    OnInitDialog 在vs2010中实现为虚函数 所以在 项目 gt 类向导 gt 虚函数 gt 选中要添加的类 xff0c 找到对应虚函数添加即可 就这么简单
  • HBITMAP与BITMAP 的区别 BMP图像的格式

    HBITMAP 是句柄 xff1b BITMAP 是实例 xff1a typedef struct tagBITMAP bm int bmType 必须是BM int bmWidth 指定位图的宽度 xff08 以象素为单位 xff09 i
  • fatal error LNK1281: 无法生成 SAFESEH 映像。

    解决方法 xff1a 1 打开该项目的 属性页 对话框 2 单击 链接器 文件夹 3 单击 命令行 属性页 4 将 SAFESEH NO 键入 附加选项 框中 xff0c 然后点击应用
  • 如何实现科技论文里面的算法

    这是一篇关于如何实现科研论文中算法的简要指南 作者曾实现过很多书本上和科研论文中的复杂算法 xff0c 在这篇文章中作者总结他在研究 xff0c 阅读 xff0c 编码和调试时积累的大量经验 很显然 xff0c 这篇文章主要集中在和计算机科
  • 程序员专用经典语录—看完笑一阵可以,千万不要死循环哦!

    IT人表示屁股上还得纹一个 lt body gt 要不中间来个hello world 真正的程序员喜欢兼卖爆米花 xff0c 他们利用CPU散发出的热量做爆米花 xff0c 可以根据米花 爆裂的速度听出正在运行什么程序 十年生死两茫茫 xf
  • android 自学中的散乱笔记

    1 查看程序运行记录 要在LogCat中查看 其内可选择查看的信息级别 xff0c 比如info xff0c error xff0c debug等等 xff0c 信息可筛选显示 2 xff1a 安装好手机驱动 xff0c 将手机接入usb即
  • java lambda表达式 闭包学习笔记

    我们把这些只拥有一个方法的接口称为函数式接口 声明一个接口是函数式接口 xff1a 编译器会根据接口的结构自行判断 xff08 判断过程并非简单的对接口方法计数 xff1a 一个接口可能冗余的定义了一个Object已经提供的方法 xff0c
  • C++ STL set和multiset的使用 hunst_xiehonghao 总结

    C 43 43 STL set和multiset的使用 std set lt int gt s 那个s这个对象里面存贮的元素是从小到大 排序的 xff0c 因为用std less作为比较工具 1 xff0c set的含义是集合 xff0c