C++ STL之map

map介绍

C++里的map数据结构,会存储键值对信息key-value,通过key得到value的信息。map的key与value有一个特点就是:每个唯一的key拥有唯一对应的value,不会出现多组value与之对应。

它和其他标准模板容器不同的是,初始化它的时候要提供两个数据类型。

比如:

map<string,int> dict;

前面一个string是key的数据类型,后者int为value的数据类型。

它的操作和属性和常见的容器差不多,像empty()、size()、begin()......

这里需要重点提一下的是它的插入操作。

map的所有元素都是pair,同时拥有实值(value)和键值(key)。pair的第一个元素会被视为键值,第二个元素会被视为实值。

 map<int ,string> maplive;

插入操作1

pair<int,string> value(1,"a");maplive.insert(value);

等价于maplive.insert(pair<int,string>(1,"a"));

插入操作2

maplive.insert(map<int,string>::value_type(1,"a"));

插入操作3

maplive[1]="a";//map中最简单最常用的插入添加!

题目练习

题目描述

输入一些单词,找出所有满足如下条件的单词:

该单词不能通过字母重排,得到输入文本中的另外一个单词。

在判断是否满足条件时,不区分大小写,但输出保留输入中的大小写,按字典序进行排列(所有大写字母在小写字母的前面)

样例输入:

ladder came tape soon leader acme RIDE lone Dreis peat

ScALE orb eye Rides dealer NotE derail LaCeS drIed

noel dire Disk mace Rob dires

样例输出:

Disk

NotE

derail

drIed

eye

ladder

soon

#define LOCAL
#include<iostream>
#include<map>
#include<string>
#include<vector>
#include<algorithm>
using namespace std; vector<string> words;
map<string,int> cnt; string repr(const string& str){//standardize
string ans=str;//!注意点1
for(int i=0;i<str.length();i++){
ans[i]=tolower(str[i]);
}
sort(ans.begin(),ans.end());//!注意点2
return ans;
} int main(){
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
string str;
while(cin>>str){
if(str[0]=='#')break;
words.push_back(str);
string r=repr(str);
if(!cnt.count(r)) cnt[r]=0;//!注意点3
cnt[r]++;
}
vector<string>ans;
//iterate vector words
for(vector<string>::iterator it=words.begin();it!=words.end();++it){
if(cnt[repr(*it)]==1) ans.push_back(*it);
}
sort(ans.begin(),ans.end());
for(int i=0;i<ans.size();i++){
cout<<ans[i];
}
}

注意点如下详细解释:

  1. 在对字符串进行标准化的时候,注意必须要对ans进行初始化。如这样string ans;是不行的。另外c++中的string真的是一等公民,既可以用下标对每一个字符进行赋值,也可以把整个字符串进行赋值,非常方便。
  2. sort函数输入两个参数,起始位置。但是它并不会返回什么的,不要以为它会返回数组的begin位置。
  3. 第三个注意点,我们这里使用的是cnt.count(r),count函数只有两个返回值(0 or 1)。如果map中有这个key,那么count就返回1,没有那么就返回0。在这里if里面的判断条件可以用!cnt[r]来替换,因为如果map中没有这个key,通过[ ]读取,它的返回值是0。所以它们的效果等同。

最新文章

  1. flex弹性盒模型布局
  2. C#读取Excel设置(亲测可用)
  3. jquery 操作select 资料
  4. 2016/10/28 很久没更了 leetcode解题 3sumcloset
  5. 【JavaScript】JavaScript模块化编程 - CommonJS, AMD 和 RequireJS之间的关系
  6. 3. 使用绘图API自定义视图 --- 旋转的方块
  7. http://blog.sina.com.cn/s/blog_7caae74b0100zl17.html
  8. 【贪心】HDU 5783 Divide the Sequence
  9. 解决MacOS Terminal打开慢的问题
  10. poj1284:欧拉函数+原根
  11. Qt5:Qt中一些函数功能介绍
  12. CSS3 Transitions 你可能不知道的知识点
  13. 将你的前端应用打包成docker镜像并部署到服务器?仅需一个脚本搞定
  14. azkaban工作流调度器及相关工具对比
  15. crawlspider_房多多
  16. app:processDebugResources
  17. 关于 uboot 的异常向量表
  18. Android-Java控制多线程执行顺序
  19. Atitit opencv 模板匹配
  20. Spring Boot干货:静态资源和拦截器处理

热门文章

  1. apk下载安装,存储的位置,路径
  2. 创建第一个windows服务
  3. 仿照jQuery进行一些简单的框架封装(欢迎指教~)
  4. 【Leetcode】【Medium】Multiply Strings
  5. 用CIFilter生成QRCode二维码图片
  6. Python学习---Python下[元组]的学习
  7. python 函数&amp;条件,循环
  8. [原]Ping azure
  9. c++新标准的一个问题
  10. PhoneGap Geolocation 获取地理位置 api