C++ STL hash_map

来源:互联网 发布:知我药妆那里来的小样 编辑:程序博客网 时间:2024/05/17 23:23
//hash_map,map,都是将记录型的元素划分为键值和映照数据两个部分;
//不同的是:hash_map采用哈希表的结构而map采用红黑树的结构;
//hash_map键值比较次数少,占用较多的空间,遍历出来的元素是非排序的而map是排序的

#include<hash_map>
#include<iostream>
using namespace std;

int main(void)
{
 hash_map<const char*,float>hm;
 //元素的插入:pair<iterator,bool>insert<const value_type &v>
 //insert(inputiterator first,inputiterator last)
 hm["apple"]=1.0f;
 hm["pear"]=1.5f;
 hm["orange"]=2.0f;
 hm["banana"]=1.8f;
 //元素的访问可以用,数组的方式也可以用迭代器的方式
 hash_map<const char*,float>::iterator i,iend,j;
 iend=hm.end();
 for(i=hm.begin();i!=iend;i++)
 {
  cout<<(*i).first<<"   "
   <<(*i).second<<endl;
 }
 cout<<"**************************************************"<<endl;
 //元素的删除erase(),clear()
 hm.erase("pear");
 for(i=hm.begin();i!=iend;i++)
 {
  cout<<(*i).first<<"   "
   <<(*i).second<<endl;
 }
 
 //元素的搜索
 j=hm.find("pear");
 i=hm.find("apple");
 cout<<"水果:"<<(*i).first<<"  "
  <<"价钱:"<<(*i).second<<endl;
 cout<<"**************************************************"<<endl;
 if(j!=hm.end())
 {
  cout<<"hash_map容器的个数"<<hm.size()<<endl;
 }
 else
 {
  cout<<"哈希表的表长:"<<hm.bucket_count()<<endl;
 }
 return 0;
}

原创粉丝点击