映射:map

映射:map

(本文为笔者个人学习笔记,如有不当之处恳请各位读者指正)

    map<key,value>是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力.例如:可以用一个map<string,int> month_name来表示“月份名称到月份编号”的映射,其中以string类型的“月份名称”作为关键字,对应的值为一个int类型的“月份编号”。然后用month_name["July"]=7这样的方式来赋值。

例:
 
简译:输入一个文本,找出文本中满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。在判断是否满足条件时,字母不区分大小写,但在输出时应保留输入中的大小写,并按字典序输出(所有大写字母在所有小写字母的前面)。
#include<iostream>
#include<string>
#include<cctype>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;


map<string,int> cnt;
vector<string> words;


// 将单词中的所有字母转化成小写,再按字典序对字母重新排列,组成新的"单词"用以统计
// 是否有两个单词由相同的字母组成.如果有,则这两个单词可由对方通过重排字母得到 
string repr(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);
		string r=repr(s);  // 将单词中的字母转化成小写
		cnt[r]++;          // 将关键字r对应的键值自增,表示将r重排可得到多少个输入中的单词 
	}
	vector<string> ans;
	for(int i=0;i<words.size();i++){
		if(cnt[repr(words[i])] == 1)  // 单词words[i]单词不能通过字母重排得到输入文本中的其他单词 
		    ans.push_back(words[i]);  // 存入输出向量 
	}
	sort(ans.begin(),ans.end());  // 按字典序输出 
	for(int i=0;i<ans.size();i++)
	    cout<<ans[i]<<"\n";
	return 0;
}
题目链接: Ananagrams - UVa 156

猜你喜欢

转载自blog.csdn.net/qq_33523482/article/details/79253567