C++之map find count

map插入值  例如map<string,int>wc;

string s;

insert(pair)------>wc.insert(make_pair(s,1))

其中insert函数是有返回值的,返回什么呢?返回一个pair

其中这个pair中的first元素是map的迭代器,second是bool,判断是否插入成功

pair<map<string,int>::iterator,bool> ret=wc.insert(make_pair(s,1));

wc.count(键值)返回0或1,代表是否存在键值

wc.find(键值)返回键值对应的second值

具体代码如下

#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
 string word;
 map<string,int>wc;
 while(cin>>word){
  pair<map<string,int>::iterator,bool> ret=wc.insert(make_pair(word,1));
  if(!ret.second){
   ++(*(ret.first)).second;
  }
 }

 map<string,int>::iterator iter=wc.begin();
 while(iter!=wc.end()){
  cout<<(*iter).first<<"   "<<(*iter).second<<endl;
  ++iter;
 }
 cout<<endl;
 cout<<wc.count("zhang")<<endl;
 cout<<wc.find("zhang")->second<<endl;
 system("pause");
 return 0;
}

 

 

你可能感兴趣的:(C++,String,iterator,insert,pair)