Namespaces
Variants
Views
Actions

std::hash<std::vector<bool>>

From cppreference.com
 
 
 
 
Defined in header <vector>
template< class Allocator >
struct hash<std::vector<bool, Allocator>>;
(since C++11)

The template specialization of std::hash for std::vector<bool> allows users to obtain hashes of objects of type std::vector<bool>.

[edit] Example

#include <iostream>
#include <unordered_set>
#include <vector>
 
using vb = std::vector<bool>;
 
vb to_vector_bool(unsigned n)
{
    vb v;
    do
    {
        v.push_back(n & 1);
        n >>= 1;
    }
    while (n);
    return v;
}
 
auto print(const vb& v, bool new_line = true)
{
    for (std::cout << "{ "; const bool e : v)
        std::cout << e << ' ';
    std::cout << '}' << (new_line ? '\n' : ' ');
}
 
int main()
{
    for (auto i{0U}; i != 8; ++i)
    {
        std::cout << std::hex << std::uppercase;
        vb v = to_vector_bool(i);
        std::cout << std::hash<vb>{}(v) << ' ' << std::dec;
        print(v);
    }
 
    // std::hash for vector<bool> makes it possible to keep them in
    // unordered_* associative containers, such as unordered_set.
 
    std::unordered_set v{vb{0}, vb{0, 0}, vb{1}, vb{1}, vb{1, 0}, vb{1, 1}};
 
    for (vb const& e : v)
        print(e, 0);
    std::cout << '\n';
}

Possible output:

6D09EE26D5863619 { 0 }
3C27D9F591D20E49 { 1 }
E74D3F72B7599C63 { 0 1 }
EE3BE81F55123770 { 1 1 }
3AAD2A2EDBEC6C35 { 0 0 1 }
EB057F773CB64C43 { 1 0 1 }
6E1354730102BE00 { 0 1 1 }
E2E622597C18899D { 1 1 1 }
{ 1 1 } { 1 0 } { 1 } { 0 0 } { 0 }

[edit] See also

(C++11)
hash function object
(class template) [edit]