題意:輸入一些單詞,找出所有滿足如下條件的單詞:單詞不能通過排列得到輸入中的另一個單詞,在判讀滿足條件時不區分大小寫,但輸出時保留原串輸出,按字典序輸出(所有大寫字母在小寫字母前面)
本題是練習map用法的一道練習題
map容器是key-value對應的一種關聯容器,即每個key對應一個value值
本題用到一些容器的基本操作,push_back(),insert()什麼的,很友善,這就是STL的魅力
疊代器(用法類似指針)是個好東西,在STL中據說是三大支柱啊
如果難了解,不妨先回去複習以下指針的使用
以下是算法競賽入門經典的劉汝佳老師的代碼,我寫了一點個人注釋幫助大家了解
當然,要更好的了解map容器的用法還是要百度看其他博文,因為我也正在學(哈哈)
#include <iostream>
#include <map>
#include <string>
#include <cctype>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
string s;
//建立map容器,特點是key-value對應關系,即一個string對應一個int值,例如dit[soon]=0;
map<string,int> dit;
//向量容器,類似于數組,操作也可以按數組方式操作,我這裡盡量使用疊代器,多練練這個牛逼的東西總是好的呀
vector<string> tit;
vector<string> out;
//傳回值是string類型
string vet(string s)
{
string ans=s;
//用疊代器周遊處理改變大寫
for(string::iterator it=ans.begin();it!=ans.end();it++)
*it=tolower(*it);
//字典序排序
sort(ans.begin(),ans.end());
return ans;
}
int main()
{
freopen("in.txt","r",stdin);
while(cin >> s)
{
if(s[0]=='#')
break;
//把新讀入的串存到向量容器裡,友善之後周遊使用
tit.push_back(s);
//按題目要求處理新讀入的串,即不能通過排列組合出現重複單詞,把這個單詞字典序排列就好了,還要改變大寫
string r=vet(s);
//讀入map容器,并獲得其value值,即出現次數,0代表唯一
if(!dit.count(r))
dit[r]=0;
else
dit[r]=1;
}
//用疊代器進行周遊,單詞唯一的就讀入新的向量容器中
for(vector<string>::iterator it=tit.begin();it!=tit.end();it++)
if(dit[vet(*it)]==0)
out.push_back(*it);
//對向量容器進行字典序排序
sort(out.begin(),out.end());
//用疊代器周遊輸出(用法類似指針,使用間接通路的形式)
for(vector<string>::iterator it=out.begin();it!=out.end();it++)
cout << *it << endl;
return 0;
}