设为首页 加入收藏

TOP

C++温习-标准库-map
2015-11-21 00:59:26 来源: 作者: 【 】 浏览:2
Tags:温习 标准 -map

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

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

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

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

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

map里面的数据存储为pair

typedef pair
   
     value_type; 
   

常用的成员变量:

value_type;//pair
   
     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
   
     #include
     using namespace std; int main() { string temp; map
     
       word_count; cout<<"please input the word your want to count, and input the ctrl+D to end of the input"<
      
       >temp) { cout<<"input word:"; // word_count[temp]++; // word_count.insert(pair
       
        (temp,1); if( word_count.find(temp)==word_count.end()) { word_count.insert(pair
        
         (temp,1)); } else { word_count[temp]++; } } int num_word=word_count.size(); cout<<"The number of word is:"<
         
          ::iterator itera; for(itera=word_count.begin();itera!=word_count.end();itera++) { cout<<"word: "<
          
           first<<" occur"<
           
            second<<" times"<
            
           
          
         
        
       
      
     
   
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++温习-标准库-set 下一篇Servlet--HttpSessionBindingList..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: