21C++ STL set multiset 一些基本操作

一些基本操作

#include<set>
using namespace std;

int main(){
	set <int> a{ 1, 2, 3, 4};
	multiset <int> b;
	
	set <int> c( a);
	multiset <int> d( a.begin(), a.end());//两个描述边界的迭代器 
	
}
#include<set>
#include<iostream>
using namespace std;

template <typename T>
void show(const T& a){
	for(auto i = a.begin(); i != a.end(); i ++)
		cout << *i << ' ';
	cout << endl;
}

template <typename T>
//定义新的排序 ——降序 
struct SortDescending{
	bool operator()(const T& a, const T& b) const{
		return ( a > b);
	}
};

int main(){
	set <int> a;
	
	//插入元素 
	a.insert(-1);
	a.insert(4);
	a.insert(1);
	a.insert(2);
	show( a);
	
	//set  b  为 降序 
	set <int, SortDescending<int>> b;// or set <int, greater<int>> b;
	b.insert(-1);
	b.insert(4);
	b.insert(1);
	b.insert(2);
	show( b);
	
	multiset <int> c{-1, 4, 1, 2};
	multiset <int> d( c);
	d.insert(4);
	show( d);
	
	//d.count 返回所查元素的 个数 
	cout << "number of 4 is " << d.count( 4) << endl;
	
}
#include<set>
#include<iostream>
using namespace std;

int main(){
	set <int> a{ 2, 1, 4, 3, 5};
	
	for(auto i = a.begin(); i != a.end(); i ++)
		cout << *i << ' ';
	cout << endl;
	
	auto p = a.find( 2);
	if( p != a.end())	cout << *p << " is found" << endl;
	else cout << "not found" << endl;
	
	auto m = a.find( 10);
	if( m != a.end())	cout << *m << " is found" << endl;
	else cout << "not found" << endl;
}
#include<set>
#include<iostream>
using namespace std;

int main(){
	multiset <int> a{ 1, 2, 3, 3, 3, 4, 5};
	for(auto i = a.begin(); i != a.end(); i ++)
		cout << *i << ' ';
	cout << endl;
	
	//1 a.erase( key) 删除值为 key 的 所有元素 
	a.erase( 3);
	for(auto i = a.begin(); i != a.end(); i ++)
		cout << *i << ' ';
	cout << endl;
	
	//2 a.erase( iterator)
	auto p = ++a.begin();
	a.erase( p);
	for(auto i = a.begin(); i != a.end(); i ++)
		cout << *i << ' ';
	cout << endl;
	
	//3 a.erase( iterator 1, iterator 2)
	a.erase( a.begin(), a.end());
	cout << a.size() << endl;
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值