码迷,mamicode.com
首页 > 编程语言 > 详细

C++温习-标准库-map

时间:2015-06-15 22:07:30      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

关于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_type
const_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;
}

C++温习-标准库-map

标签:

原文地址:http://blog.csdn.net/chenriwei2/article/details/46508509

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!