map使用方法 (STL)

1.
        map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。对于迭代器来说,可以修改实值,而不能修改key。
2.
        建立Key - value的对应时,key 和 value可以是任意你需要的类型。 
根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。
3.
         map映射默认是按key值升序排列的,并且key值是不允许重复的,一般情况输入新的键-值对时,如果key是重复的,新的键-值对会覆盖旧的。
4.
map最基本的构造函数;
map<string , int >test;         map<int ,string >test;
        map<sring, char;>test         map< char ,string>test;
        map<char ,int>test;            map<int ,char >test;
5.
        operator[key]:特殊函数,仅用在单映射map类中,可以以数组形式给映射添加键-值对,并可返回值的引用。
        map(int,string)test;
        test[1]="aaa";
        cout<<test[1]<<endl;
6.
        insert():插入函数,用operater[]的方式插入键-值对非常直观(下面例1的赋值方式),但存在一个性能的问题。插入1时,先在test中查找主键为1的项,没发现,然后将一个新的对象插入test,键是1,值是一个空字符串,插入完成后,将字符串赋为"aaa"; 该方法会将每个值都赋为缺省值,然后再赋为显示的值,如果元素是类对象,则开销比较大,下面例2和例3可以避免这种大开销。例1中如果再赋值test[1]="iii",则原来的值会被覆盖;例2中如果再赋值(3,"iii"),则会赋值失败,该方式插入单个键-值对时,会返回插入位置和成功标志,插入位置已经存在值时,插入失败;例3是在指定位置插入,在不同位置插入效率是不一样的,因为涉及到重排。
        map<int ,string> test;  
        1).test[1]="aaa";//map中最常用的插入添加方式!
        2).test.insert(pair<int,string>(3,"bbb"));
        3).test.insert(map<int,string>::value_type(5,"ccc"));
        map<int,string>::iterator  res;
        res=test.end();
        4).test.insert(res,pair<int,string>(7,"ddd"));
返回插入位置以及是否插入成功:
        pair<map<char, int>::iterator, bool> res;
        res = test.insert(pair<char, int>('a', 100));
        if (res.second == false) 
        {
            cout << "element 'a' already existed";
            cout << " with a value of " << res.first->second << '\n';
        }
指定插入位置,效率更高:
        map<char, int>::iterator it = test.begin();
        test.insert(it, pair<char, int>('b', 200));  
        test.insert(it, pair<char, int>('c', 300));  
范围多值插入:
        map<char, int> test2;
        test2.insert(test.begin(), test.find('c'));
列表形式插入,C++11开始支持:
        test2.insert({ { 'd', 100 }, {'e', 200} });
使用{}赋值是从c++11开始的,因此编译器版本过低时会报错(如visual studio 2012):
        map<int, string> test = {{ 1, "aaa" },{ 3, "bbb" },{ 5, "ccc" } };
7.
find():查找函数,以key为关键字查询,找到则返回指向该关键字的迭代器,否则返回指向end的迭代器,根据map的类型,返回的迭代器为 iterator 或者   const_iterator,
map<char,int>test;
map<char,int>::iterator res;
test['a']=100;
test['b']=200;
res=test.find('b');
if(res!=test.end())
test.erase(res);
8.
size():元素个数统计。
max_size():容器最多能容纳的元素个数。
map<int,string>test;
int  count=test.size();
int  count=test.max_size();
9.
count():统计某一个key值出现的次数,一般只返回1或者0,在单一map中不允许重复key,可以用来判断某个元素是否存在。
int count=test.count(3);
10.
empty():判断容器是否为空,返回bool值。
if(!test.empty())printf("it is empty.");
11.
erase():删除函数,可以依据key值来删,也可以依据迭代指针来删,还可以范围删除。
map<int,string>test;
map<int,string>::iterator res;
test[1]="aaa";
test[2]="bb";
res=test.find(2)
test.erase(1);  //根据key值删除
test.erase(res); //根据迭代指针删除
test.erase(test.begin(),test.end())//范围删除,全部删除时等价clear();
12.
lower_bound():返回键值大于等于key的迭代指针。
upper_bound():返回键值大于key的迭代指针。
map<int,string>test;
map<int,string>::iterator res;
test[1]="aaa"
test[2]="bbb"
res=lower_bound(1);//返回key为1的迭代指针
res=upper_bound(1);//返回key为2的迭代指针
13.
key_comp():以(key1,key2)为参数,比较key的先后顺序,key1<ke2则返回1,否则返回0。
value_comp():以(*res1,*res2)两组键-值对为参数,比较元素的存放顺序,但其实仍然可以理解为比较key的先后顺序。
int ans=test.value_comp()(*test.find(3),*test.find(1));
int ans=test.key_comp()(3,1);
14.
swap():交换两个容器的元素。
map<string,string>t1;map<string,string>t2;map<string,string>t3;
t1["a"]="aaa";t2["a"]="bbb";t3["a"]="ccc";
swap(t1,t2);  //交换t1、t2的元素
t3.swap(t2);  //交换t2、t3的元素
15.
begin():  返回容器第一个元素的迭代指针。
end():     返回容器最后一个元素后面的结束标识的迭代指针。
rbegin():返回容器最后一个元素的逆向迭代指针。
rend():   返回容器第一个元素前面的开始标识的逆向迭代指针。
res=test.begin();
while(res!=test.end())
{ cout<<(*res).second<<endl; res++;}//正向顺序打印容器中的所有元素
res=test.rbegin();
while(res!=rend())

{ cout<<(*res).second<<endl; res++;}//逆向顺序打印容器中的所有元素

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{ 
	int count;
	map<int,string>test;
	map<int,string>::iterator res;
	// insert()
	test[1]="aaa";
	test[3]="bbb";
	test.insert(pair<int,string>(5,"ccc"));
	test.insert(pair<int,string>(7,"ddd"));
	res=test.begin();
	while(res != test.end())
	{
		cout<<(* res).first<<"\t"<<(* res).second<<endl;
	    res++;
	}
	cout<<"\n"<<endl;

	// find()
	res=test.find(0);
	if(res!=test.end())
		cout <<"find test[0] is: "<< (* res).second <<endl;
	else
		cout<< "cannot find test[0] !" << endl;
	res=test.find(1);
	if(res!=test.end())
		cout <<"find test[1] is: "<<(* res).second <<endl;
	else
		cout<< "cannot find test[1] !" << endl;
	cout<<"\n"<<endl;

    //size()
    count=test.size();
	cout <<"the num of member is: "<< count << endl;
	count=test.max_size();
	cout <<"the max_num of member is: "<< count << endl;
	cout<<"\n"<<endl;

	//count()
	count=test.count(3);
	cout<<"key 3 appear "<<count <<" times!"<<endl;
	count=test.count(2);
	cout<<"key 2 appear "<<count <<" times!"<<endl;
    cout<<"\n"<<endl;

	//empty()
	if(!test.empty())
		cout<<"test.empty() is: "<<test.empty()<< endl;
    cout<<"\n"<<endl;

	//erase(key)
	test[9]="eee";
    res=test.find(9);
	cout<<"test[9] "<<(* res).second<<" exist."<<endl;
	test.erase(9);
	res=test.find(9);
	if(res!=test.end())
		cout <<"find test[9] is: "<< (* res).second <<endl;
	else
		cout<< "test[9] has been erased!" << endl;
	cout<<"\n"<<endl;

	//erase(iterator res)
	test[-1]="***";
	res=test.find(-1);
	cout<<"test[-1] "<<(* res).second<<" exist."<<endl;
	test.erase(res);
	res=test.find(-1);
	if(res!=test.end())
		cout <<"find test[-1] is: "<< (* res).second <<endl;
	else
		cout<< "test[-1] has been erased!" << endl;
	cout<<"\n"<<endl;

     //erase(begin(),end())
	test[-1]="iii";
	test[-2]="jjj";
	res=test.begin();
	cout<<"before erase:"<<endl;
	while(res!=test.end())
	{   
		cout<<(*res).first<<"  "<<(*res).second<<endl;
		res++;
	}
    test.erase(test.begin(),test.find(1));
    res=test.begin();
	cout<<"after erase:"<<endl;
	while(res!=test.end())
	{
		cout<<(*res).first<<"  "<<(*res).second<<endl;
		res++;
	}
	cout<<"\n"<<endl;

	//lower_bound(),upper_bound()
	res=test.lower_bound(-5);
	cout<<"first time key>=-5,key is: "<<(*res).first<<" "<<(*res).second<<endl;
	res=test.lower_bound(3);
	cout<<"first time key>=3,key is: "<<(*res).first<<" "<<(*res).second<<endl;
	res=test.upper_bound(-5);
	cout<<"first time key>-5,key is: "<<(*res).first<<" "<<(*res).second<<endl;
	res=test.upper_bound(3);
	cout<<"first time key>3,key is: "<<(*res).first<<" "<<(*res).second<<endl;
	cout<<"\n"<<endl;

	//value_comp()
	test[-1]="iii";
	test[9]="aaa";
	res=test.begin();
	while(res!=test.end())
	{
		cout<<(*res).first<<"  "<<(*res).second<<endl;
		res++;
	}
	int ans=test.value_comp()(*test.find(3),*test.find(-1));
	cout<<"compare(3,-1),ans is: "<<ans<<endl;
	ans=test.value_comp()(*test.find(3),*test.find(1));
	cout<<"compare(3,1),ans is: "<<ans<<endl;
	ans=test.value_comp()(*test.find(3),*test.find(3));
	cout<<"compare(3,3),ans is: "<<ans<<endl;
	ans=test.value_comp()(*test.find(3),*test.find(5));
	cout<<"compare(3,5),ans is: "<<ans<<endl;	
	ans=test.value_comp()(*test.find(3),*test.find(9));
	cout<<"compare(3,9),ans is: "<<ans<<endl;
    cout<<"\n"<<endl;

	//key_comp()
	ans=test.key_comp()(3,1);
	cout<<"key_comp(3,1),ans is: "<<ans<<endl;
	ans=test.key_comp()(3,3);
	cout<<"key_comp(3,3),ans is: "<<ans<<endl;
	ans=test.key_comp()(3,5);
	cout<<"key_comp(3,5),ans is: "<<ans<<endl;
	cout<<"\n"<<endl;
    
	//swap()
    map<string,string>t1;
	map<string,string>t2;
	map<string,string>t3;
	t1["a"]="aaa";
	t2["a"]="bbb";
	t3["a"]="ccc";
	swap(t1,t2);
	cout<<"after swap: "<<"t1['a']: "<<t1["a"]<<" t2['a']: "<<t2["a"]<<endl;
	t3.swap(t2);
	cout<<"after swap: "<<"t2['a']: "<<t2["a"]<<" t3['a']: "<<t3["a"]<<endl;
    cout<<"\n"<<endl;

    //rbegin(),rend()
	map<int,string>::reverse_iterator rev;
	rev=test.rbegin();
	while(rev!=test.rend())
	{
    	cout<<"reverse :"<<(*rev).first<<"  "<<(*rev).second<<endl;
		rev++;
	}
	return 0;
}
上面代码的Output如下:

1       aaa
3       bbb
5       ccc
7       ddd


cannot find test[0] !
find test[1] is: aaa


the num of member is: 4
the max_num of member is: 268435455


key 3 appear 1 times!
key 2 appear 0 times!


test.empty() is: 0


test[9] eee exist.
test[9] has been erased!


test[-1] *** exist.
test[-1] has been erased!


before erase:
-2  jjj
-1  iii
1  aaa
3  bbb
5  ccc
7  ddd
after erase:
1  aaa
3  bbb
5  ccc
7  ddd


first time key>=-5,key is: 1 aaa
first time key>=3,key is: 3 bbb
first time key>-5,key is: 1 aaa
first time key>3,key is: 5 ccc


-1  iii
1  aaa
3  bbb
5  ccc
7  ddd
9  aaa
compare(3,-1),ans is: 0
compare(3,1),ans is: 0
compare(3,3),ans is: 0
compare(3,5),ans is: 1
compare(3,9),ans is: 1


key_comp(3,1),ans is: 0
key_comp(3,3),ans is: 0
key_comp(3,5),ans is: 1


after swap: t1['a']: bbb t2['a']: aaa
after swap: t2['a']: ccc t3['a']: aaa


reverse :9  aaa
reverse :7  ddd
reverse :5  ccc
reverse :3  bbb
reverse :1  aaa
reverse :-1  iii
Press any key to continue



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值