set容器的常用方法

#include "stdafx.h"
#include <iostream>
#include <string>
#include <set>
using namespace std;

int main(int argc, char* argv[])
{
	set<int> s;
	//添加元素
	s.insert(5); 
	s.insert(8);
	s.insert(7);
	s.insert(9);
	s.insert(1);
	//遍历容器
	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;
	//删除元素
	s.erase(8);
	for(it = s.begin(); it != s.end(); it++)
		cout << *it << " ";
	cout << endl;	
	//清空容器
	s.clear(); //set容器清空
	if( s.empty() )  //判断set容器是否为空
		cout << "The s is empty!" << endl;
	else
		cout << "The s is not empty!" << endl;	
	//查找元素
	it = s.find(20);
	if(it != s.end())
		cout << "Find it" << endl;
	else
		cout << "Can't fint it" << endl;

	multiset<string> ms;
	multiset<string>::iterator msit;
	//添加元素
	ms.insert("lzh");
	ms.insert("lzy");
	ms.insert("123");
	ms.insert("lzh");
	for(msit = ms.begin(); msit != ms.end(); msit++)
	{
		cout << *msit << " ";
	}
	cout << endl;
	//删除元素
	cout << "删除123元素:" << endl;
	ms.erase("123");
	for(msit = ms.begin(); msit != ms.end(); msit++)
	{
		cout << *msit << " ";
	}
	cout << endl;
	cout << "删除首元素:" << endl;
	ms.erase(ms.begin());
	for(msit = ms.begin(); msit != ms.end(); msit++)
	{
		cout << *msit << " ";
	}
	cout << endl;
	//查找元素
	cout << "查找lzh:" << endl;
	if(ms.find("lzh") != ms.end())
		cout << "success" << endl;
	else
		cout << "not find it" << endl;

	return 0;
}

输出:

1 5 7 8 9
9 8 7 5 1
1 5 7 9
The s is empty!
Can't fint it
123 lzh lzh lzy
删除123元素:
lzh lzh lzy
删除首元素:
lzh lzy
查找lzh:
success

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值