C++ set使用

set集合容器,就是一个存放集合的容器,存储时候自动判断是否与已存在元素相同,相同的话自觉跳过。

自定义元素存放方式,比如mycomp函数元素从大到小存放。

struct mycomp{	// 自定义比较函数mycomp 
	bool operator() (const int &a,const int &b){
			return a>b;	// "()"重载运算符 
	}
};

set<int,mycomp> s; 声明变量

主要有下面这些函数:

  1. s.insert(k); 插入元素
  2. s.erase(k); set删除元素
  3. s.clear(); set集合容器清空
  4. s.size(); set集合容量
  5. s.find(k); 元素查找,返回迭代器位置

multiset 多重集合容器:
multiset<string> p; //multiset 多重集合容器(允许有重复元素的
int k=p.erase("123123"); //multiset删除元素,多个的话全部删除并统计个数

#include <iostream>
#include <vector>
#include <string>
#include <set>
using namespace std;

struct mycomp{							// 自定义比较函数mycomp 
	bool operator() (const int &a,const int &b){
			return a>b;					// "()"重载运算符 
	}
};
struct info{							// set中结构体元素 
	string name;						//  "<" 重载运算符 
	double score;
	bool operator< (const info &a) const{
		return a.score<score;
	}
};

int main()
{
	set<int,mycomp> s;					// set自定义比较函数mycomp 
	 
	s.insert(8);						// 插入元素 
	s.insert(12);
	s.insert(98);
	s.insert(8);						// 重复插入元素的时候不会执行 
	s.insert(75);
	set<int>::iterator it;				// 迭代器 
	for(it=s.begin();it!=s.end();it++)
		cout<<*it<<" ";
	cout<<endl;
	set<int>::reverse_iterator rit;		// 反向迭代器 
	for(rit=s.rbegin();rit!=s.rend();rit++)
		cout<<*rit<<" ";
	cout<<endl;
	it=s.find(3);						// set集合元素检索 
	if(it!=s.end())
		cout<<*it<<endl;
	else
		cout<<"not found it!"<<endl;
	s.erase(12);						// set删除元素 
	s.clear(); 							// set集合容器清空 
	s.size();  							// set集合容器的容量 
	
	multiset<string> p;					//multiset 多重集合容器(允许有重复元素的集合)
	p.insert("123123");
	p.insert("123123");
	p.insert("abc");
	p.insert("bcd");
	int k=p.erase("123123");			// multiset删除元素,多个的话
	全部删除并统计个数 

	multiset<string>::iterator fp;
	for(fp=p.begin();fp!=p.end();fp++)
		cout<<*fp<<" ";
	cout<<k<<endl;
	fp=p.find("abc");					// 元素查找 
	cout<<*fp<<endl;
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值