集合:set與映射:map
Set 就是數學上的集合:每個元素最多隻能出現一次
Set exmple
Andy‘s First Dictionary Uva 10815 例題可查
#include <iostream>
#include <string>
#include <cstring>
#include <set>
#include <sstream>
using namespace std;
set<string> dict;
int main()
{
string s,buf;
while(cin>>s)
{
if(s[0]=='#')
break;
cout<<s.length();
for(int i=0;i<s.length();i++)
{
if(isalpha(s[i]))
s[i]=tolower(s[i]); //isalpha()是爲了表示判斷s[i]其是否是字母,是就用tolower轉換成小寫,不是就輸出空格。
else
s[i]=' ';
}
stringstream ss(s);
cout<<"ss >> buf"<<endl;
while(ss >> buf)
dict.insert(buf);
}
for(set<string>:: iterator it=dict.begin();it!=dict.end();++it)//迭代器iterator相當於是個類型 it是一個變量 基類型是iterator 它從開始掃到結尾的前一個【據TY菌解釋 像數組一樣 最後一位是沒有值的 數組是一個結束標誌 不知集合最後是什麼】輸出的時候 由於it掃描的是地址 要輸出*it
{
cout<<*it<<endl;
}
return 0;
}
映射:map
map是從健(key)到值(value)的映射,由於重載了[]運算符,map如數組的高級版
例:map<string,int>month_name 表示月份名字到月份編號的映射“例month_name["July"]=9的賦值方式”
exmple:
反片語:ananagrams,156
輸入一些單詞,找出所有滿足如下條件的單詞:該單詞不能通過字母重排,得到輸入文本中的另一個單詞“在這一句提的理解時我對題目沒有讀懂,最後理解了,就是輸入的單詞不能夠重新排列,得到輸入的那些文本中的單詞,自己有點懵逼沒讀懂,小白真可怕,我要努力了”。在判斷是否滿足條件時,字母不區分大小寫,但在輸出時應該保留輸入中的大小寫,按字典序進行排列(所有大寫字母在小寫字母的前面)
利用map (string,int)的功能,定義一個map(string,int) cnt,用cnt[string]表示string出現的次數。把每個單詞“標準化”,即全部轉換爲小寫後進行排序,然後再放入到map中進行統計
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
map<string,int> cnt; //集合聲明
vector<string> words; //容器聲明
string repr(const string& s)
{
string ans = s;
for(int i=0;i<s.length();i++)
{
ans[i]=tolower(ans[i]);//將字符串轉化爲小寫字母
}
sort(ans.begin(),ans.end());// 回顧sort中的知識,排序對象存儲在vector中,調用方式是sort(v.begin(),v.end),普通數組的調用方式是sort(a,a+n)的方式調用
return ans;
}
int main()
{
string s;
while(cin>>s)
{
if(s[0]=='#')
break;
words.push_back(s);
string r=repr(s);
if(!cnt.count(r)) cnt[r]=0;
cnt[r]++;
}
vector<string> ans;
for(int i=0;i<words.size();i++)
{
if(cnt[repr(words[i])]==1)
ans.push_back(words[i]);
}
sort(ans.begin(),ans.end());
for(int i=0;i<ans.size();i++)
cout<<ans[i]<<endl;
return 0;
}
具體的代碼註釋我會有時間添加完整,現在11點,我先洗洗啦。加油,大白超................................................................