標籤:stream algorithm 關係 技術 erase for set isp char
map 容器儲存索引值對,提供了很好的一對一的關係。
在內部,元素總按特定的規則有序,通常用二叉搜尋樹實現。
下面是使用樣本:
#include <cstdio>#include <algorithm>#include <set>#include <map>#include <iostream>using namespace std;int main () { map<char,int> mymap; //first insert method mymap.insert(pair<char,int>(‘a‘,100)); mymap.insert(pair<char,int>(‘z‘,200)); //insert函數的傳回值類型4 pair<map<char,int>::iterator,bool> ret; ret=mymap.insert(pair<char,int>(‘z‘,500)); if(ret.second==false) { cout<<"element ‘z‘ already existed"<<endl; cout<<"with a value of "<<ret.first->second<<endl; } //second insert method map<char,int>::iterator it=mymap.begin(); mymap.insert(it,pair<char,int>(‘b‘,300)); mymap.insert(it,pair<char,int>(‘c‘,400)); //third insert method map<char,int> anothermap; anothermap.insert(mymap.begin(),mymap.find(‘c‘)); cout<<"mymap contains:"<<endl; for(it=mymap.begin();it!=mymap.end();it++) cout<<it->first<<" => "<<it->second<<endl; cout<<"anothermap contains:"<<endl; for(it=anothermap.begin();it!=anothermap.end();it++) cout<<it->first<<" => "<<it->second<<endl; map<char,int> m; map<char,int>::iterator itlow,itup; m[‘a‘]=20; m[‘b‘]=40; m[‘c‘]=60; m[‘d‘]=80; m[‘e‘]=100; itlow=m.lower_bound(‘b‘); itup=m.upper_bound(‘d‘); cout<<itlow->second<<" "<<itup->second<<endl; m.erase(itlow,itup); cout<<"m contains:"<<endl; for(it=m.begin();it!=m.end();it++) cout<<it->first<<" => "<<it->second<<endl;}
map
與multimap
差別僅僅在於其中的 ‘multiple‘——允許一個鍵對應多個值。
多維map
好像之前發過這題
#include <cstdio>#include <algorithm>#include <set>#include <map>#include <iostream>#include <string>using namespace std;map<string,string> m;int main (){ string t; cin>>t; string k,v; while(true) { cin>>v; if(v=="END") break; cin>>k; m[k]=v; } cin>>t; string text; getline(cin,text); while(1) { getline(cin,text); if(text=="END") break; int i=0; while(i<text.length()) { string word=""; while(text[i]>=65&&text[i]<=90||text[i]>=97&&text[i]<=122) { word+=text[i]; i++; } if(!(text[i]>=65&&text[i]<=90||text[i]>=97&&text[i]<=122)) { i++; } if(m.count(word)) { string new_word=m[word]; int sub=new_word.length()-word.length(); i+=sub; text.replace(text.find(word),word.length(),new_word); } } cout<<text<<endl; } return 0;}
View Code
c++ map