set(集合)、 map(映射表)、 multiset(多键集合) 、multimap(多键映射表),这些容器均以RB-tree完成(是一种比较均衡的二叉树);
hash_set(散列集合)、hash_map(散列映射表)、hash_multiset(散列多键集合)、hash_multimap(散列多键映射表)是以hashtable(散列表--一种链表数组)为底层机制完成。
#if 0
c++STL__hash_set (2009-09-21 09:54:11)转载▼
标签: 教育
// |(hash_set)|
//**************************************************************
//| #0桶 | #1桶 | #2桶 | #3桶 | #4桶 | #5桶 | #6桶 |
//**************************************************************
// ||
// \ /
// \/
// 每个桶用vector容器实现,桶里存放着,通过hash(x)=x%7计算得到相同
// 值的元素,x的确定:假设n为要存放的元素个数,则x为,第一个不小于x的指数
#include<hash_set>
#include<iostream>
using namespace std;
struct strequal{
bool operator()(const char*s1,const char* s2)const{
return strcmp(s1,s2)==0;
}
};
int main(void)
{
hash_set<int> hs;
//元素的插入:pair<iterator,bool>insert(const value_type &v)
//insert(inputiterator first,inputiterator last)
hs.insert(1);
hs.insert(101);
hs.insert(91);
hs.insert(41);
//元素的遍历:没有反相遍历
hash_set<int>::iterator i,iend;
iend=hs.end();
for(i=hs.begin();i!=iend;i++)
{
cout<<*i<<" ";
}
cout<<endl<<"**********************************************"<<endl;
//元素的删除:erase(),clear()
hs.erase(41);
for(i=hs.begin();i!=iend;i++)
{
cout<<*i<<" ";
}
cout<<endl<<"**********************************************"<<endl;
//元素的搜索:find()
//搜索元素""banana"
hash_set<char *,hash<char*>,strequal>hs1;//hash<char*>为哈希函数对象,strequal键值比较函数对象
hs1.insert("apple"); //元素的哈希地址:hash<char*>%n
hs1.insert("banana");
hs1.insert("pear");
hash_set<char*,hash<char*>,strequal>::iterator j;
j=hs1.find("banana");
cout<<"查找到的水果名称是:"<<*j;
cout<<endl<<"**********************************************"<<endl;
cout<<"hs1容器是否为空:"<<hs1.empty()<<endl;
cout<<"hs1容器的元素个数:"<<hs1.size()<<endl;
cout<<"hs1容器的表长:"<<hs1.bucket_count()<<endl;
return 0;
}
#endif
#if 0
//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;
}
#endif