Map是STL的一個關聯容器,它提供一對一(其中第一個能夠稱爲關鍵字,每一個關鍵字只能在map中出現一次,第二個可能稱爲該關鍵字的值)的數據 處理能力,因爲這個特性, 它完成有可能在咱們處理一對一數據的時候,在編程上提供快速通道。這裏說下map內部數據的組織,map內部自建一顆紅黑樹(一 種非嚴格意義上的平衡二叉樹),這顆樹具備對數據自動排序的功能,因此在map內部全部的數據都是有序的。
功能:創建key-value的映射 key與value是任何你須要的類型 exp:map<char,int> a 創建一個char到int的映射a。ios
經常使用語句:begin()返回map頭部迭代器編程
end()返回尾部迭代器ide
clear()清空全部元素函數
erase()刪除一個元素spa
find()查找一個元素code
empty()若是爲空則返回true排序
size()返回map大小ci
count(elem)返回某個元素個數字符串
例題:UVa 156 -反片語input
大意是給你幾串字符串 求出自身字符隨意組合後不會出如今這些字符串裏面的字符串 按字典序排序。
ladder came tape soon leader acme RIDE lone Dreis peat ScAlE orb eye Rides dealer NotE derail LaCeS drIed noel dire Disk mace Rob dries #
Disk NotE derail drIed eye ladder soon
分析
這道題的解法不少,最簡化的方式就是使用map容器。想到使用「標準化」。
總體思路:
1.寫一個標準化函數(實現大寫字母轉換爲小寫(tolower()函數),單詞排序。注意使用const是爲了避免改變s的初值)
2.兩個vector容器(words,ans),一個map容器(cnt)
words存儲全部的單詞
map存儲標準化後對應單詞以及出現次數的值,至關於一個表格。
words通過查表map,把對應的符合值給ans
感受初次寫map仍是挺爽的...
#include<iostream>#include<map>#include<vector>#include<string>#include<algorithm>using namespace std;map<string,int>mmap;vector<string> str;string standard(const string &s){ string t=s; for(int i=0;i<s.size();i++) { t[i]=tolower(s[i]);//轉換成小寫字母 } sort(t.begin(),t.end()); return t;}int main(){ string s; while(cin>>s) { if(s[0]=='#') break; str.push_back(s);//推入vector string r=standard(s);//將其標準化 mmap[r]++; } vector<string>ans; for(vector<string>::iterator it=str.begin();it!=str.end();it++) { if(mmap[standard(*it)]==1) ans.push_back(*it); } sort(ans.begin(),ans.end()); for(vector<string>::iterator it=ans.begin();it!=ans.end();it++) { cout<<*it<<endl; } return 0; }