C++ STL 学习笔记-关联容器 set/multiset、map/multimap简单使用方法及注意事项

set/multiset

     set内部元素依据其值自动排序,每个元素只能出现一次不能重复,multiset与set相同,只不过允许元素重复

1. 底层数据结构: 红黑树.

2. 支持的函数:

  insert()    插入元素

  clear()     清空元素

  erase()    删除元素

  empty()   为空返回1,不为空返回0

  find()       查找函数

#include "stdafx.h"
#include <set>
#include <iostream>
using namespace std;
using std::set;
using std::cout;
typedef set<int> _Set;
typedef multiset<int> _MSet;
typedef set<int>::iterator _It;
typedef multiset<int>::iterator _MIt;
void printSet(_Set s)
{
	for(_It it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
	_Set iset;
	//_MSet iset;
	//_MIt it;
	_It it;
	iset.insert(5);
	iset.insert(8);
	iset.insert(9);
	iset.insert(50);
	iset.insert(39);
	iset.insert(9);

	printSet(iset);
	it = iset.find(8);
	if(it != iset.end())
	{
		cout << "find 8" << endl;
		iset.erase(it);
	}
	cout << endl;
	printSet(iset);
	iset.clear();
	if(iset.empty())
	{
		cout << "is empty" <<endl;
	}
	return 0;
}

map/multimap

      map元素是键值对(key/value),每个元素都有一个键,是排序的基础,每个键只能出现一次,不允许重复,mutimap与map相同,只不过允许重复

1.底层数据结构:红黑树

2.支持的函数:

  insert()    插入元素

  clear()     删除元素

  erase()    删除元素

  empty()   为空返回1,不为空返回0

  find()       查找函数

#include "stdafx.h"
#include <map>
#include <iostream>
using namespace std;
using std::map;
using std::cout;
struct ltstr
{
	bool operator()(const char* s1,const char* s2) const
	{
		return strcmp(s1,s2) < 0;
	}
};
typedef map<const char*,int,ltstr> mapContainer;
typedef map<const char*,int,ltstr>::iterator mapiter;
void printMap(mapContainer m)
{
	for(mapiter it = m.begin(); it != m.end(); it++)
	{
		cout <<"["<<it->first <<","<< it->second <<"]"<< endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	  mapContainer m;
	  mapiter it;
   m.insert(pair<const char *,int>("Lily",29));
   m.insert(pair<const char *,int>("Lucy",19));
   m.insert(map<const char *,int>::value_type("Mack",50));
   m["jack"] = 3;
   printMap(m);
   m.erase("Lily");
   printMap(m);
   it = m.find("Lucy");
   if(it != m.end())
   {
	   cout << "found lucy" << endl;
   }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值