一.insert()
直接上直接上代码,两种方式:
map<string,int> m_map;
也就是说,insert后面的数据是pair类型或者是value_type类型了,然而对C++有了解的人都明白,其实value_type和pair<const k,v>是等价的、insert()中的参数必须是value_type类型,那么为什么insert()中的参数能够使用make_pair产生的pair<k,v>呢?
其实,因为我们在加入pair<k,v>时的k已经是常量了,所以可以加入。。。而正常来讲这都是所有编译器所能接受的。
在insert插入的同时,还有返回值来说明是否插入成功,就是pair< map<string,int>::iterator,bool> >类型,如本实例pair< map<string,int>::iterator,bool> > rent= m_map.insert(make_pair("hello",5));
rent.second即是成功与否的标志;rent.first就是返回的map<string,int>::iterator迭代器;rent.first->first就是string类型的数据。
二.find()
map< string,vector<string> > children;
map< string,vector<string> >::iterator iter=children.find(famName);
返回类型是map<>::iterator,如果没有找到就返回children.end(),以此可以判断是否找到。
根据返回值获得对应的value:
vector<string>::iterator it=iter->second.begin(); //本来直接iter->second就是value了,但是value是vector容器,所以这里实际得到了value的迭代器其实位置。
while(it!=iter->second.end())
cout<<*it++<<endl;
下面结合以上两个函数对map进行操作:.定义一个map对象,其元素的键是家族姓氏,而值则是存储该家族孩子名字的vector对象。为这个map容器输入至少六个条目。通过基于家族姓氏的查询检测你的程序,查询应输出该家族所有孩子的名字
int main()
{
map< string,vector<string> > children;
string famName,childName;
do
{
cout<<"input families‘ name:"<<endl;
cin>>famName;
if(!cin)
break;
vector<string> chd;
pair< map<string,vector<string> >::iterator,bool > ret=children.insert(make_pair(famName,chd));
if(!ret.second)
{
cout<<"already exist the family name:"<<famName<<endl;
continue;
}
cout<<"\n\tinput children‘s name:"<<endl;
while(cin>>childName)
ret.first->second.push_back(childName);
cin.clear();
}while(cin);
cin.clear();
cout<<"input a family name to search:"<<endl;
cin>>famName;
map< string,vector<string> >::iterator iter=children.find(famName);
if(iter==children.end())
cout<<"\n\tsorry there is not this familyname: "<<famName<<endl;
else
{
cout<<"\n\tchildren:"<<endl;
vector<string>::iterator it=iter->second.begin();
while(it!=iter->second.end())
cout<<*it++<<endl;
}
return 0;
}
原文:http://blog.csdn.net/jiangheng0535/article/details/20131333