STL之set、map基本使用实例

set和map都是关联式容器,二者都对内部元素默认排序:升序。

set是key结构 , map是key-value结构;

set可以去重 , map重载了[ ],查询速度快;


set包含的基本方法:


map的基本方法



使用这些函数的实例

void test_set()
{
	//set是 key结构的,是关联式容器,对插入的元素自动排序,默认是升序
	set<int> Myset;
	set<int> ::iterator it;
	cout << "insert() , size() , begin() , end() " << endl;
	Myset.insert(5);
	Myset.insert(3);
	Myset.insert(1);
	Myset.insert(7);
	cout << Myset.size() << endl;
	cout << Myset.max_size() << endl;
	for (it = Myset.begin(); it != Myset.end(); ++it)
	{
		cout << "   " << *it;
	}
	cout << endl;

	cout << " find(),  erase() ,  clear()   , empty() 测试:" << endl;

	it = Myset.find(5);
	Myset.erase(it, Myset.end());   //删除Myset的it到end之间的元素
	for (it = Myset.begin(); it != Myset.end(); ++it)
	{
		cout << "   " << *it;
	}
	cout << endl;

	cout << Myset.empty() << endl;
}


void test_map()
{
	map<string, int> Mymap;
	cout << "insert()  , begin() , clear( ) 测试:" << endl;
	Mymap.insert(pair<string ,int>("vector", 1));  //插入 key-value 
	Mymap.insert(pair<string ,int>("map", 4));
	Mymap.insert(pair<string ,int>("set", 3));
	Mymap.insert(pair<string ,int>("list", 2));
	map<string, int>::const_iterator  it;
	for (it = Mymap.begin(); it != Mymap.end(); ++it)
	{
		cout << it->first << "~~" << it->second<< endl;  //!!!这里编译不通过,肯定是你没有包含string头文件!
	}
	cout << "[] , find() ,  count(), clear() , size() , empty() " << endl;
	cout << Mymap["map"] << endl;

	it = Mymap.find("list");  //find() 查找一个元素
	cout << (*it).first << " : " << (*it).second<< endl;

	cout << Mymap.count("map") << endl;//count() 返回指定元素出现的次数
	
	cout << Mymap.size() << endl;

	Mymap.clear();
	cout<< Mymap.empty() << endl;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值