当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++ map练习

C++ map练习

2019年03月02日  | 移动技术网IT编程  | 我要评论

鲅鱼圈天气,qq311,飞机高铁上网将提速

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。所以它们的效果等同。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网