10
22
2015
0

stl::map基本操作<更新>

本质上也用到了二叉搜索树,是维护键与键对应值的容器~

#include<cstdio>
#include<map>
#include<cstring>
#include<string>
using namespace std;
int main()
{
	//声明 first键,second值
	map<int,const char*> m;
	//const char*字符型数组
	//map<int,string> m;
	
	//插入元素写法1
	m.insert(make_pair(1,"ONE"));
	m.insert(make_pair(10,"TEN"));
	//typedef pair<int,const char*> p;
	//m.insert(p(10,"TEN"));
	//插入元素写法2
	m[100]="HUNDRED";

	//查找元素写法1
	map<int,const char*>::iterator it;
	it=m.find(1);
	puts(it->second);//迭代器相当于指针而非结构体
	it=m.find(2);
	if(it==m.end()) puts("not found");
	else puts(it->second);
	//查找元素写法2
	puts(m[10]);
	//puts(m[11]);
	
	//删除元素
	m.erase(10);
	
	//遍历所有元素
	for(it=m.begin();it!=m.end();++it)
		printf("%d: %s\n",it->first,it->second);
	return 0;
}

输出结果:

上述注释掉的代码或多或少都有些问题,所以尽量还是用程序中的写法吧:

  • 定义string类型需要头文件#include<string>,注意只有#include<cstring>是不行的
  • int键对应字符串值时,最好用字符型数组,string类型编译没有通过 。注意字符型数组表示为const char*
  • UPD:值可以是string型
  • 用pair时不需头文件定义。插入时make_pair()即可。定义一个pair的写法运行时发生错误
  • 查找元素的第二种写法,即直接puts(map[i]) 若运行注释掉的语句 输出如下:

 UPD:

  • 另外一些基本操作:
    cout<<"map 的 max_size 的值:"<<studentMessage.max_size()<<endl;
    cout<<"map 的 size 的值:"<<studentMessage.size()<<endl;

    studentMessage.clear();
    if(studentMessage.empty())
    {
        cout<<"The map is Empty !!"<<endl;
    }
    else
    {
        cout<<"The map is not Empty !!"<<endl;
    }
  • 查找:

findkey)可确定查找元素的位置

countkey

因为map中的值不允许重复,所以一个值只能出现一次,

这说明count的返回值就只能是01,即可完成查找操作

但是用count来完成查找并不是最优的选择,因为原来的本意是用count来完成计数的,(这在vector等序列式容器中非常好用,而map中之所以有这个count函数,就是为了STL提供统一的接口,这样说来map中的upper_boundlower_boundequel_range等函数组合起来也可完成查找功能)

 

Category: STL | Tags: STL | Read Count: 581

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com