首页 > 编程语言 > 详细

C++ map练习

时间:2019-03-01 18:40:40      阅读:156      评论:0      收藏:0      [点我收藏+]

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];
    }
}

C++ map练习

原文:https://www.cnblogs.com/MarkKobs-blog/p/10458122.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!