无序关联容器之unordered_set

https://en.cppreference.com/w/cpp/container/unordered_set

  • 头文件

<unordered_set>

  • 声明

(1)    (since C++11)

template<
    class Key,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator<Key>
> class unordered_set;
(2)    (since C++17)
namespace pmr {
    template <class Key,
              class Hash = std::hash<Key>,
              class Pred = std::equal_to<Key>>
    using unordered_set = std::unordered_set<Key, Hash, Pred,
                                             std::pmr::polymorphic_allocator<Key>>;
}

  • 描述

unordered_set是一个关联容器,它包含有类型Key的一个集合,该集合内的每个key只有一个对象。搜索、插入和删除都是平均固定时间复杂度。

本质上,元素没有进行任何的排序,它是以"桶"的方式组织的。把元素放在哪个“桶”里依赖于该元素的hash值。这样会进行快速的访问,因为,一旦hash值出来,它就可以索引到特定的"桶"。

容器内的元素不能被修改,因为一旦修改,就会引起元素hash值的变化。

std::unordered_set meets the requirements of Container, AllocatorAwareContainer, UnorderedAssociativeContainer.

  • 迭代器和非法情况
操作非法情况
所有只读操作,swap和std::swap
clear, rehash, reserve, operator=全非法
insert, emplace, emplace_hint只有引起rehash时非法
erase只有指向被删除的元素时,非法
  • 成员类型
类型定义
key_typeKey
value_typeKey
size_typeUnsigned integer type (usually std::size_t)
difference_typeSigned integer type (usually std::ptrdiff_t)
hasherHash
key_equalKeyEqual
allocator_typeAllocator
referenceAllocator::reference    (until C++11)    value_type&    (since C++11) 
const_referenceAllocator::const_reference    (until C++11)    const value_type&    (since C++11) 
pointer    Allocator::pointer    (until C++11)    std::allocator_traits<Allocator>::pointer    (since C++11) 
const_pointer  Allocator::const_pointer    (until C++11)    std::allocator_traits<Allocator>::const_pointer    (since C++11) 
iterator  LegacyBidirectionalIterator
const_iterator Constant LegacyBidirectionalIterator
local_iterator An iterator type whose category, value, difference, pointer and reference types are the same as iterator. This iterator can be used to iterate through a single bucket but not across buckets.
const_local_iteratorAn iterator type whose category, value, difference, pointer and reference types are the same as const_iterator. This iterator can be used to iterate through a single bucket but not across buckets.
node_type(since C++17)   a specialization of node handle representing a container node
insert_return_type(since C++17)

 type describing the result of inserting a node_type, a specialization of
template <class Iter, class NodeType> struct /*unspecified*/ {
    Iter     position;
    bool     inserted;
    NodeType node;
};

instantiated with template arguments iterator and node_type.

  • 迭代器
begin
cbegin
returns an iterator to the beginning
(public member function)
end
cend
returns an iterator to the end
(public member function)
  • 指标
emptychecks whether the container is empty
(public member function)
sizereturns the number of elements
(public member function)
max_sizereturns the maximum possible number of elements
(public member function)
  • 修改
clearvoid clear() noexcept;
(since C++11)
clears the contents
(public member function)
insert(1)    (since C++11)
std::pair<iterator,bool> insert( const value_type& value );
(2)    (since C++11)
std::pair<iterator,bool> insert( value_type&& value );
(3)    (since C++11)
iterator insert( const_iterator hint, const value_type& value );
(4)    (since C++11)
iterator insert( const_iterator hint, value_type&& value );
(5)    (since C++11)
template< class InputIt >void insert( InputIt first, InputIt last );
(6)    (since C++11)
void insert( std::initializer_list<value_type> ilist );
(7)    (since C++17)
insert_return_type insert(node_type&& nh);
(8)    (since C++17)
iterator insert(const_iterator hint, node_type&& nh);
inserts elements or nodes (since C++17)
(public member function)
emplacetemplate< class... Args >std::pair<iterator,bool> emplace( Args&&... args );
(since C++11)
constructs element in-place
(public member function)
emplace_hinttemplate <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args );
(since C++11)
constructs elements in-place using a hint
(public member function)
erase(1)    (since C++11)
iterator erase( const_iterator pos );
(2)    (since C++11)
iterator erase( const_iterator first, const_iterator last );
(3)    (since C++11)
size_type erase( const key_type& key );
erases elements
(public member function)
swap(since C++11)(until C++17)
void swap( unordered_set& other );
(since C++17)
void swap( unordered_set& other ) noexcept(/* see below */);
swaps the contents
(public member function)
extract(1)    (since C++17)
node_type extract( const_iterator position );
(2)    (since C++17)
node_type extract( const key_type& x );
(C++17)extracts nodes from the container
(public member function)
merge(1)    (since C++17)
template<class H2, class P2>void merge(std::unordered_set<Key, H2, P2, Allocator>& source);
(2)    (since C++17)
template<class H2, class P2>void merge(std::unordered_set<Key, H2, P2, Allocator>&& source);
(3)    (since C++17)
template<class H2, class P2>void merge(std::unordered_multiset<Key, H2, P2, Allocator>& source);
(4)    (since C++17)
template<class H2, class P2>void merge(std::unordered_multiset<Key, H2, P2, Allocator>&& source);
(C++17)splices nodes from another container
(public member function)
  • 查找
count(1)    (since C++11)
size_type count( const Key& key ) const;
(2)    (since C++20)
template< class K >size_type count( const K& x ) const;
returns the number of elements matching specific key
(public member function)
find(1)
iterator find( const Key& key );
(2)        
const_iterator find( const Key& key ) const;
(3)    (since C++20)
template< class K > iterator find( const K& x );
(4)    (since C++20)
template< class K > const_iterator find( const K& x ) const;
finds element with specific key
(public member function)
contains(1)    (since C++20)
bool contains( const Key& key ) const;
(2)    (since C++20)
template< class K > bool contains( const K& x ) const;
(C++20)
 checks if the container contains element with specific key(public member function)
equal_range(1)    (since C++11)
std::pair<iterator,iterator> equal_range( const Key& key );
(2)    (since C++11)
std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const;
(3)    (since C++20)
template< class K >std::pair<iterator,iterator> equal_range( const K& x );
(4)    (since C++20)
template< class K >std::pair<const_iterator,const_iterator> equal_range( const K& x ) const;
returns range of elements matching a specific key
(public member function)
  • 桶接口
begin(size_type)
cbegin(size_type)
returns an iterator to the beginning of the specified bucket
(public member function)
end(size_type)
cend(size_type)
returns an iterator to the end of the specified bucket
(public member function)
bucket_countreturns the number of buckets
(public member function)
max_bucket_countreturns the maximum number of buckets
(public member function)
bucket_sizereturns the number of elements in specific bucket
(public member function)
bucketreturns the bucket for specific key
(public member function)
  • hash策略
load_factorfloat load_factor() const;
(since C++11)
returns average number of elements per bucket
(public member function)
max_load_factor

(1)    (since C++11)

float max_load_factor() const;
(2)    (since C++11)

void max_load_factor( float ml );

manages maximum average number of elements per bucket
(public member function)
rehashvoid rehash( size_type count );
(since C++11)
reserves at least the specified number of buckets.
This regenerates the hash table.
(public member function)
reservevoid reserve( size_type count );
(since C++11)
reserves space for at least the specified number of elements.
This regenerates the hash table.
(public member function)
  • 观测器
hash_functionreturns function used to hash the keys
(public member function)
key_eqreturns the function used to compare keys for equality
(public member function)

 

  • Notes

The member types iterator and const_iterator may be aliases to the same type. This means defining a pair of function overloads using the two types as parameter types may violate the One Definition Rule. Since iterator is convertible to const_iterator, a single function with a const_iterator as parameter type will work instead.

  • 举例

#include <iostream>
#include <string>
#include <array>
#include <unordered_set>

int main ()
{
  std::unordered_set<std::string> myset = {"yellow","green","blue"};
  std::array<std::string,2> myarray = {"black","white"};
  std::string mystring = "red";

  myset.insert (mystring);                        // copy insertion
  myset.insert (mystring+"dish");                 // move insertion
  myset.insert (myarray.begin(), myarray.end());  // range insertion
  myset.insert ( {"purple","orange"} );           // initializer list insertion

  std::cout << "myset contains:";
  for (const std::string& x: myset) std::cout << " " << x;
  std::cout <<  std::endl;

  return 0;
}

#include <iostream>
#include <string>
#include <array>
#include <unordered_set>

int main ()
{
  std::unordered_set<std::string> myset = {"yellow","green","blue"};
  std::array<std::string,2> myarray = {"black","white"};
  std::string mystring = "red";

  myset.insert (mystring);                        // copy insertion
  myset.insert (mystring+"dish");                 // move insertion
  myset.insert (myarray.begin(), myarray.end());  // range insertion
  myset.insert ( {"purple","orange"} );           // initializer list insertion

  std::cout << "myset contains:";
  for (const std::string& x: myset) std::cout << " " << x;
  std::cout <<  std::endl;

  return 0;
}
 

输出:

./unorder_set.out 
myset contains: orange purple white black reddish yellow green blue red

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值