【C++学习】map

来源:互联网 发布:越狱铃声软件 编辑:程序博客网 时间:2024/06/06 05:45

关于map,也就是字典,kv键值对。

在C++中,它是一个类模板,它是属于一个关联容器类模板

template < class Key,                                     // map::key_type           class T,                                       // map::mapped_type           class Compare = less<Key>,                     // map::key_compare           class Alloc = allocator<pair<const Key,T> >    // map::allocator_type           > class map;

我们在新建map类型的时候,必须提供Key 和Value的类型,可选提供比较器和配置器,一般只是在使用自己的类型的时候,才需要提供。

map中,Key是唯一的,不能有多个相同的key,而且都是按照key的大小排序的,也就是说map都是自动排序的,

map里面的数据存储为pair

typedef pair<const Key, T> value_type;

常用的成员变量:

value_type;//pair<const key_type,mapped_type>iterator;//迭代器,指向value_typeconst_iterator;//常量迭代器reverse_iterator;//逆向迭代器const_reverse_iterator;//常量,逆向

常用的成员函数:

//1. 迭代器begin();end();rbegin();rend();cbegin();//以下C++11新加入cend();crbegin();crend();//以上都是返回迭代器,其中r开头的表示返回的是逆向的迭代器,c开头的表示返回的是const迭代器。//2. 容量:empty();//测试map是否为空size();//返回容器的大小;//3. 获取元素operator[];//可以像普通的数组一样的方式使用。at(const key_type& k);//C++11新加方法。//4. 增删改查insert(const value_type& val);//增erase(iterator position);//删size_type erase (const key_type& k);//删void erase (iterator first, iterator last);//删clear();//删除所有的数据。find (const key_type& k);//查count (const key_type& k);//与find有点功能重复,因为map的key是唯一的,所以count只能返回两个值,0或者1,分别表示存在这个key或者不存在。

字典应该是平时编程中很经常用到的一个数据结构。比如,有时候需要计算一篇文章中的每个单词出现的次数,以形成文章的词向量。

#include<iostream>#include<map>using namespace std;int main(){    string temp;    map<string,int> word_count;    cout<<"please input the word your want to count, and input the ctrl+D to end of the input"<<endl;    while(cin>>temp)    {    cout<<"input word:";       // word_count[temp]++;        // word_count.insert(pair<string,int>(temp,1);         if( word_count.find(temp)==word_count.end())         {         word_count.insert(pair<string,int>(temp,1));     }     else      {         word_count[temp]++;      }    }    int num_word=word_count.size();    cout<<"The number of word is:"<<num_word<<endl;    map<string,int>::iterator itera;    for(itera=word_count.begin();itera!=word_count.end();itera++)    {        cout<<"word: "<<itera->first<<" occur"<<itera->second<<" times"<<endl;    }    cout<<"done"<<endl;    return 0;}
0 0
原创粉丝点击