map/multimap容器
- map基本概念
 - map构造和赋值
 - map的大小和交换
 - map插入和删除
 - map的查找和统计
 
- map排序
 
map基本概念
map中的所有元素都是pair对组,高效率,pair中的第一个元素为key(键值),起到索引作用,第二个元素为value(实值),所有元素都会根据元素的键值自动排序。map/multimap属于关联式容器,底层结构是用而二叉树实现。可以根据key值快速找到value值。map和multimap的区别是map不允许容器中有重复key值元素;multimap允许容器中有重复key值元素。
map构造和赋值
1、map<T1,T2> mp;默认构造函数
 2、map(const map &mp);拷贝构造函数
 3、map& operator=(const map &mp);赋值
void p(const map<int,int>&s) {
	for (map<int,int>::const_iterator it = s.begin();it != s.end();it++) {
		cout << "Key:" << (*it).first << "\tValue:" << it->second << endl;;
	}
	cout << endl;
}
void test1() {
	map<int, int> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 24));
	m.insert(pair<int, int>(3, 15));
	m.insert(pair<int, int>(4, 57));
	p(m);
	map<int, int> m2(m);
	p(m2);
	map<int, int>m3;
	m3 = m2;
	p(m3);
}
 
map的大小和交换
1、empty();判断容器是否为空
 2、size();返回容器中元素的个数
 3、swap(st);交换两个集合容器
void test1() {
	...
	if (!m.empty()) {
		cout << "不为空" << endl;
		cout << "大小:" << m.size() << endl;
	}
	...
	m1.swap(m);
	p(m);
}
 
map插入和删除
1、insert(elem);插入,只有这一种方法
 2、clear();清空所有元素
 3、erase(pos);删除pos位置的元素,返回下一个数据的位置
 4、erase(beg,end);删除迭代器从beg到end之间的元素,返回下一个数据的位置
 5、erase(key);删除容器中值为key的元素
void test1() {
	...
	m.erase(m.begin());
	m.erase(++m.begin(), --m.end());
	p(m);
	m.erase(2);
	p(m);
	m.clear();
	p(m);
}
 

map的查找和统计
1、find(key);查找key是否存在,若存在,返回该键的元素的迭代器,若不存在,返回set.end()
 2、count(key);统计key的元素个数
void test1() {
	...
	map<int,int>::iterator pos = m.find(40);
	if (pos != m.end()) {
		cout << "查到元素的key=" << (*pos).first << "查到元素的value=" << (*pos).second << endl;
	}
	else {
		cout << "没找到" << endl;
	}
	cout << m.count(1)<<endl;//统计的结果式0或1
}
 
map排序
利用仿函数改变排序规则,默认升序从小到大。在定义时确定排序规则。
class MyCompare {
public:
	bool operator()( int v1, int v2)const {
		return v1 > v2;
	}
};
//内置类型排序
void test1() {
	...
	//按key排序
	for (map<int, int, MyCompare>::const_iterator it = m.begin();it != m.end();it++) {
		cout << "Key:" << (*it).first << "\tValue:" << it->second << endl;;
	}
}
                


















