STL--映射:map

2023-12-28 13:47:33

map的介绍

? ? ? ?map就是从键到值的映射。因为重载了[]运算符,map像是数组的“高级版”。例如可以用map<string,int>month_name来表示“月份名字到月份编号”的映射,然后用month_name["July"]=7这样的方式来赋值。支持insert,find,count,remove等操作。

map的应用

题目

? ? ? ?输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。在判断是否满足条件时,字母不分大小写,但在输出时应保留输入中的大小写,按字典序进行排列(所有大写字母在所有小写字母的前面)。

样例输入
ladder came tape soon leader acme?RIDE?lone Dreis peatScAlE orb eye Rides dealer NotE derail LaCeS drIednoel dire Disk mace Rob dries

样例输出
Disk
NotE
derail
drIed
eye
ladder
soon

代码

#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){//将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);
		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]<<"\n";
	}
	return 0;
}

文章来源:https://blog.csdn.net/m0_72674633/article/details/135263454
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。