您的位置:首页 > 理论基础 > 数据结构算法

数据结构应用标准模版库STL—— map的操作

2013-12-06 12:29 316 查看




#include<iostream>
#include<map>
#include<string>
using namespace std;
 int main()
 {
	 map<string,int> student;
	student["a"]=10;
	student["b"]=20;
	student["c"]=30;
	student["d"]=40;
	student["e"]=50;
	student["f"]=60;
	student["g"]=70;
	student["h"]=80;
	cout<<"***************************************"<<endl;
	cout<<"size of student:"<<student.size()<<endl;  //打印元素个数
	map<string,int>::iterator iter=student.begin ();
	
	 iter=student.find ("bc");  //查找"bc",如果找到iter->second=true;否则iter->second==false;
	 if(iter->second==false)
		 cout<<"find "<<iter->first<<":"<<iter->second<<endl;
	 else cout<<"no find bc"<<endl;

	cout<<"a=>"<<student.find("a")->second<<endl;   //查找
	
	cout<<"***************************************"<<endl;
	cout<<"erase(student.begin()):    "<<endl;  
	student.erase(student.begin());   //删除第一个元素
	cout<<"size of student:"<<student.size()<<endl;
		iter=student.begin();
	 while(iter!=student.end())
	 {
		cout<<iter->first<<":"<<iter->second<<endl;
		iter++;
	 }

	cout<<"***************************************"<<endl;
	 	cout<<"erase(student.begin(),student.end()):    "<<endl;  //删除开始到结束的所有
		student.erase(student.begin() ,student.end());
		cout<<"size of student:"<<student.size()<<endl; 

	cout<<"***************************************"<<endl;//插入操作
	iter=student.begin ();
	student.insert (pair<string,int>("x",100));  //方法1
	student.insert (pair<string,int>("y",110));
	student.insert (pair<string,int>("z",120));
	student.insert (student.find("z"),pair<string,int>("a",130));  //方法2
	cout<<"size of student:"<<student.size()<<endl; 
	iter=student.begin ();
	while(iter!=student.end())
	{
		cout<<iter->first<<":"<<iter->second<<endl;
		iter++;
	}
	pair<map<string,int>::iterator ,bool > ret;  //方法3
	ret=student.insert(pair<string,int>("x",111));
	if(ret.second==false)  //该处应该是ret.second 不能是ret->second
	{	cout<<"element x is already existed";
		 cout<<" with a value of "<<ret.first->second<<endl;
	}
		cout<<"size of student:"<<student.size()<<endl; 

		return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: