关闭

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

标签: map数据结构iteratorC++stl
620人阅读 评论(0) 收藏 举报
分类:

#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;

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:71542次
    • 积分:1398
    • 等级:
    • 排名:千里之外
    • 原创:64篇
    • 转载:1篇
    • 译文:2篇
    • 评论:24条
    最新评论