STL学习(四)关联容器
一.set
(一)简介
- 集合容器,通过实值来排序,通过实值来查找
- 特点
 高效访问
 和map数据结构都是红黑树(节点链起来的,因此不支持随机访问)
 map是分键值对,set键值即实值,实值即键值,键值不能重复
(二)操作
- 排序顺序
 默认为从小到大
 加上仿函数greater之后为从大到小
#include<iostream>
#include<set>
#include<algorithm>
#include<functional>
using namespace std;
void fun(int x);
int main()
{
	cout << "默认从小到大" << endl;
	set<int> st1;
	st1.insert(15);
	st1.insert(12);
	st1.insert(18);
	st1.insert(14);
	
	for_each(st1.begin(), st1.end(), fun);
	cout << endl;
	cout << "从大到小排序" << endl;
	set<int, greater<>> st2;
	st2.insert(15);
	st2.insert(12);
	st2.insert(13);
	st2.insert(14);
	for_each(st2.begin(), st2.end(), fun);
	cout << endl;
	system("pause");
	return 0;
}
void fun(int x)
{
	cout << x << " ";
}

 2.插入
 只提供insert函数
 3.属性
 size(),没有capacity(),因为本质和链表类似(迭代器也只能++操作)
 4.删除
 earse()和clear()
 5.查找
- find(elem) //找到返回elem元素迭代器,找不到返回end(),即set容器最后一个元素的后一个迭代器
- count(elem) //查找elem个数,对于set来说,找到返回1找不到返回0
- lower_bound(elem) //返回第一个>=elem元素的迭代器(注意不是小于是大于等于)
- upper_bound(elem) //返回第一个>elem的元素的迭代器(注意没有等于)
二.multiset
可以重复的set集合,其他和set类似
三.map
(一)简介
键值保存,高效访问,低效插入,只能改value
(二)操作
- 插入(insert)
 插入键值对,用pair<T,T>(_ ,_ ) pi
 pair实质为一个结构体,里面封装了frist和second变量,分别对应key和value,因此输出时只需要输出pi.frist,pi.second,迭代器访问方法:ite->first,ite->second
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
int main()
{
	map<int, string> mp;
	mp.insert(pair<int, string>(100, "张三"));
	pair<int, string> pi(101, "李四");
	mp.insert(pi);
	cout <<"学号:"<< pi.first << "姓名:" << pi.second << endl;
	map<int, string>::iterator ite = mp.begin();
	cout <<"学号:"<< ite->first << "姓名:" << ite->second << endl;
	system("pause");
	return 0;
}

2.查找
- find(key) //查找键值,找到返回该键迭代器,找不到返回end(),即map容器最后一个元素的后一个迭代器
- count(key) //查找key的个数,对于map最多只有一个,对于multimap可有多个
- lower_bound(key) //返回第一个>=key元素的迭代器(注意不是小于是大于等于)
- upper_bound(key) //返回第一个>key的元素的迭代器(注意没有等于)
四.multimap
头文件< map>
 允许key重复计数count(),其他和map类似
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号