1. 程式人生 > >映射:map專題

映射:map專題

src closed 方式 運算符 復雜度 圖片 nbsp const 就是

概念:摘自《算法競賽入門經典》——劉汝佳:map就是從鍵(key)到值(value)的映射。因為重載了[]運算符,map像是數組的“高級版”。

例如可以用一個map<string, int> month_name 來表示“月份名字到月份編號”的映射然後用month_name["July"] = 7 這樣的方式來賦值。

Map中的元素是自動按key升序排序,所以不能對map用sort函數:

map的功能:

1. 自動建立Key - value的對應。key 和 value可以是任意你需要的類型。
2. 根據key值快速查找記錄,查找的復雜度基本是Log(N),如果有1000個記錄,最多查找10次,1,000,000個記錄,最多查找20次。
3. 快速插入Key - Value 記錄。
4. 快速刪除記錄
5. 根據Key 修改value記錄。
6. 遍歷所有記錄。

map多用於查找很方便快捷,尤其是以鍵和值的形式存在的。在大量數據中使用map,查詢效率很高。

舉例:

map<int, string> student;
student.insert(pair<int, string>(54090101, "Mike"));
student.insert(pair<int, string>(54090102, "MIKE"));
student.insert(map<int, string>::value_type(54090103, "Sam"));
student.insert(map<int, string>::value_type(54090104, "SAM"));
student[54090105] = "Jake";
student[54090105] = "JAKE";//鍵值為標識,重復插入,結果為替換
studentMessage[54090104] = "Bob";
studentMessage[54090105] = "Ben";

遍歷
map<int, string>::iterator iter;
for (iter = student.begin(); iter != student.end(); ++iter)
{
cout << iter->first << ": " << iter->second << endl;
}

C++ map的基本操作和使用:

http://blog.sina.com.cn/s/blog_61533c9b0100fa7w.html

例題uva 156

技術分享圖片
#include<iostream>
#include
<string> #include<cctype> #include<vector> #include<map> #include<algorithm> using namespace std; map<string,int> cnt; vector<string>words; //將單詞s進行標準化 即全為小數且字符都是排序的 string repr(const string& s) { string ans=s; for(int i=0;i<ans.length();i++) { ans[i]=tolower(ans[i]); } sort(ans.begin(),ans.end()); return ans; } int main() { int n=0; string s; while(cin>>s) { if(s[0]==#) break; words.push_back(s);//向vector數據結構中添加元素 string r=repr(s); //開始map裏面沒有內容,它的初始化值是:{},即裏邊有0個鍵值對 if(cnt.count(r)==0) //檢驗被查找的r是否存在,存在返回1,否則為0 cnt[r]=0; cnt[r]++;//記錄每個字符串s搜查之後為s1,統計各個s1的鍵值 } vector<string> ans; for(int i=0;i<words.size();i++) if(cnt[repr(words[i])]==1)//說明重排也無重復字符串 ans.push_back(words[i]);//向vector數據結構中添加元素 sort(ans.begin(),ans.end());//按順序排序 for(int i=0;i<ans.size();i++) cout<<ans[i]<<"\n"; return 0; }
View Code

映射:map專題