STL----map容器

1基本概念

在這裏插入圖片描述

2map常用函數

2.1構造函數

在這裏插入圖片描述

2.2賦值操作

在這裏插入圖片描述

2.3大小操作

在這裏插入圖片描述

2.4插入刪除操作

在這裏插入圖片描述

2.5刪除元素

在這裏插入圖片描述

2.6map查找元素

在這裏插入圖片描述

2.7實例

#include<iostream>
#include<map>
using namespace std;
void Printf(map<int,int>& m){
	for(map<int,int>::iterator it=m.begin();it!=m.end();it++){
		cout<<it->first<<" "<<it->second<<endl;
	}
}
void test01(){
	map<int,int> m;
	//插入方式
	//第一種
	m.insert(pair<int,int>(1,10));
	//第二種
	m.insert(make_pair(2,20));
	//第3種
	m.insert(map<int,int>::value_type(3,30));
	//第四種
	m[4]=40;
	//注意
	m[5];//會自動創建一個key爲5 value爲0的數據
	Printf(m);
}
//刪除查找
void test02(){
	map<int,int> m;
	m.insert(pair<int,int>(1,10));
	m.insert(make_pair(2,20));
	m.insert(map<int,int>::value_type(3,30));
	m[4]=40;
	//刪除
	m.erase(3);//按照key值來刪除;

	//查找
	map<int,int>::iterator pos=m.find(4);
	if(pos!=m.end()){
		cout<<" 找到key=40的元素了"<<endl;
	}
	//統計
	cout<<m.count(4)<<endl;

	//lower_bound //返回第一個key>=keyelem元素的迭代器 
	map<int,int>::iterator ret=m.lower_bound(2);
	if(ret!=m.end()){
		cout<<"找到key=20的元素了"<<ret->first<<"     "<<ret->second<<endl;
	}
	
	//upper_bound //返回第一個key>keyelem元素的迭代器 
	ret=m.upper_bound(2);
	if(ret!=m.end()){
		cout<<"找到key=20的元素了"<<ret->first<<"     "<<ret->second<<endl;
	}
	
	//equal_bound //返回第一個key>=keyelem元素的迭代器 
	pair<map<int,int>::iterator,map<int,int>::iterator> it=m.equal_range(2);
	if(it.first!=m.end()){
		cout<<"找到equal_rang的lower_bound元素了"<<it.first->first<<"     "<<it.first->second<<endl;
		
	}
	if(it.second!=m.end()){
		cout<<"找到equal_rang的upper_bound元素了"<<it.second->first<<"     "<<it.second->second<<endl;
		
	}
}
int main(){
	test04();
}





3指定map容器的排序規則

class Mycompare{
public:
	bool operator()(int n1,int n2){
		return n1>n2;
	}

};
void test04(){
	map<int,int,Mycompare> m;
	m.insert(pair<int,int>(1,10));
	m.insert(make_pair(2,20));
	m.insert(map<int,int>::value_type(3,30));
	m[4]=40;
	m[5];
	for(map<int,int,Mycompare>::iterator it=m.begin();it!=m.end();it++){
		cout<<it->first<<" "<<it->second<<endl;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章