unordered_set (2)

unordered_set::bucket_size()

size_type bucket_size ( size_type n ) const;

返回第N个存储桶中的元素数量。

存储桶是容器内部哈希表的一个插槽,根据哈希值为其分配元素。

存储桶中的元素数量会影响访问存储桶中特定元素所需的时间。容器会自动增加存储桶的数量,以使负载系数(即平均存储桶大小)低于其max_load_factor

参数:n  ---存储桶编号,应低于Bucket_count

例子:

#include<iostream>
#include<unordered_set>
#include<string>
int main()
{
    std::unordered_set<std::string> myset={ "red","green","blue","purple","pink"};
    unsigned int nBuckets=myset.bucket_count();
    
    std::cout<<"myset has"<<nBuckets<<"buckets\n";
    for(auto i=0;i<nBuckets;i++)
        std::cout<<"bucket #"<<i<<"has"<<myset.bucket_size(i)<<"elements\n";
    
    return 0;
}

可能的输出:

myset有7个桶:
bucket#0有1个元素。
bucket#1有1个元素。
bucket#2有2个元素。
bucket#3有0个元素。
bucket#4有1个元素。
bucket#5有1个元素。
bucket#6有0个元素。

unordered_set::count()

size_type count ( const key_type& k ) const;

计算特定键的数量。在容器中搜索值为k的元素,并返回找到的元素数。因为unordered_set容器不允许重复值,这意味着如果容器中存在具有该值的元素,则该函数实际返回1,否则返回零。即查找容器中是否含有这个元素。

返回值:如果找到值等于k的元素,则返回1,否则返回0。

例子:

#include<iostream>
#include<unordered_set>
int main()
{
    std::unordered_set<std::string> myset={"hat", "umbrella", "suit"};
    for(auto& x:{"hat","sunglasses","suit","t-shirt"})
        if(count(x)>0)
            std::cout<<"myset has the element"<<x;
        else
            std::cout<<"myset don't has the element:"<<x;
    return 0;
}

输出:

myset has hat
myset has no sunglasses
myset has suit
myset has no t-shirt

unordered_set::find() 

      iterator find ( const key_type& k );
const_iterator find ( const key_type& k ) const;

在容器中搜索k为value的元素,如果找到则返回迭代器,否则返回iterator到unordered_set :: end()(超过容器末尾的元素)。

另一个成员函数unordered_set :: count()可用于检查特定元素是否存在。unordered_set中的所有迭代器都具有对const元素访问权限(即使那些类型没有以const_为前缀的元素):可以插入或删除元素,但在容器中不能修改元素。

返回值:

如果找到指定的值,则为该元素的迭代器;如果在容器中未找到,则为unordered_set :: end()。

#include<iostream>
#include<unordered_set>
#include<string>
int main()
{
    std::unordered_set<std::string> myset={"red","green","blue" };

    std::string input;
    std::cout << "color? ";
    getline(std::cin,input);
    
    std::unordered_set<string>::const_iterator cit=myset.find(input);
    if(cit!=myset.end())
        std::cout<<"myset has the element:"<<*cit<<std::endl;
     else
        std::cout<<"myset don't has the element"<<std::endl;
}

unordered_map 和unordered_set有什么区别?

unordered_map是利用key值找到对应的value的,而unordered_set的value值就是它的Key值。都是利用hash表和散列函数实现的。

unordered_map与map

虽然都是map,但是内部结构大大的不同哎,map的内部结构是R-B-tree来实现的,所以保证了一个稳定的动态操作时间,查询、插入、删除都是O(logN),最坏和平均都是。而unordered_map如前所述,是哈希表。顺便提一下,哈希表的查询时间虽然是O(1),但是并不是unordered_map查询时间一定比map短,因为实际情况中还要考虑到数据量,而且unordered_map的hash函数的构造速度也没那么快,所以不能一概而论,应该具体情况具体分析。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值