Unordered container, unorderedmap

Source: Internet
Author: User

Unordered container, unorderedmap

Hash container ):
Generally, the access efficiency is higher than that of binary tree storage.
# Include <boost/unordered_set.hpp>
# Include <boost/unordered_map.hpp>
Using namespace boost;
Hash set introduction:
The unordered Library provides two hash collection classes: unordered_set and unordered_multiset. The STLport also provides hash_set and hash_multiset. Their interfaces are used in the same way as the standard associated containers set/multiset in stl, however, the binary tree is replaced by a hash internally, so the search complexity is reduced from the number to the constant.
Brief declaration of unordered_set/unordered_multiset:
Template <class Key, class Hash = boost: hash <Key>,
Class Pred = std: pai_to <Key>,
Class Alloc = std: allocator <Key>
Class unordered_set;

Template <class Key, class Hash = boost: hash <Key>,
Class Pred = std: pai_to <Key>,
Class Alloc = std: allocator <Key>
Class unordered_multiset;
Compared with std: set, the unorder_set template adds a template type parameter for calculating the hash value, usually boost: hash. It is best not to change it, in addition, the comparison predicate parameter uses std: into _to <> instead of less <> in set, because the hash container does not need to be in order.

Usage of a hash set:
Note the no-Order of the hash container. binary_search, lower_bound, and upper_bound cannot be used on the hash container for the sorted interval algorithm. The hash container itself does not provide such a member function.
Example: The program defines a template function hash_func () to operate hash_set/unordered_set. The two functions are identical. First, use boost: assign to initialize the hash set, traverse the output by iterator, use size () to display the container size, clear the set with clear (), insert () to insert two elements, and use find () to find the elements, finally, use erase () to delete an element, which is a standard operation of the standard container.

# Include <iostream>
# Include # Include <boost/unordered_set.hpp>
# Include <boost/assign/list_of.hpp>
Using namespace boost;
Using namespace std;
Template <typename T>
Void hash_func ()
{
Using namespace boost: assign;
T s = (list_of (1), 2, 3, 4, 5); // initialize data
For (T: iterator p = s. begin (); p! = S. end (); ++ p) // use the iterator to traverse the set
{Cout <* p <"";}
Cout <endl;
Cout <s. size () <endl;
S. clear ();
Cout <s. empty () <endl;
S. insert (8 );
S. insert (45 );
Cout <s. size () <endl;
Cout <* s. find (8) <endl;
S. erase (45 );
}

Int main ()
{
Hash_func <unordered_set <int> ();
System ("pause ");
Return 0;
}

Introduction to hash ing:
The unordered database provides two hash ing classes: undorderd_map and unordered_multimap. Their interfaces are used in the same way as the standard associated container map/multimap in stl, but the binary tree is replaced by the hash table internally, A hash calculation function is added to the template parameters, and the comparison predicate uses the escape _to <>.
Brief declaration of unordered_map and unordered_multimap:
Template <class Key, class Mapped,
Class Hash = boost: hash <Key>,
Class Pred = std: pai_to <Key>,
Class Alloc = std: allocator <Key>
Class unordered_map;

Template <class Key, class Mapped,
Class Hash = boost: hash <Key>,
Class Pred = std: pai_to <Key>,
Class Alloc = std: allocator <Key>
Class unordered_multimap;
Usage of hash ing:
Unordered_map/unordered_multimap is an associated container that uses std: pair to store data in the key-value format. It can be understood as an associated array and provides operator [] overload. Its usage is the same as that of the standard container map.
Unordered_multimap allows repeated key-value ing, so operator [] is not provided.
Example:
# Include <iostream>
# Include # Include <boost/unordered_map.hpp>
# Include <boost/assign/list_of.hpp>
# Include <boost/typeof. hpp>
Using namespace boost;
Using namespace std;
Using namespace stdext;
Int main ()
{
Using namespace boost: assign;
// Use assign for initialization
Unordered_map <int, string> um = map_list_of (1, "one") (2, "two") (3, "three ");
Um. insert (make_pair (10, "ten "));
Cout <um [10] <endl;
Um [11] = "eleven ";
Um [15] = "fifteen ";
For (BOOST_AUTO (p, um. begin (); p! = Um. end (); ++ p)
Cout <p-> first <"-" <p-> second <",";
Cout <endl;
Um. erase (11 );
Cout <um. size () <endl;
Hash_map <int, string> hm = map_list_of (4, "four") (5, "five") (6, "six ");
For (BOOST_AUTO (p, hmbegin (); p! = Hm. end (); ++ p)
Cout <p-> first <"-" <p-> second <",";
Cout <endl;
System ("pause ");
Return 0;
}

Performance Comparison:
Example: The program uses the boost random library random () to insert 10000 integers between 1 and 100 to the container, and then execute the count and find operations;
# Include <iostream>
# Include <typeinfo>
# Include # Include <set>
# Include <boost/unordered_set.hpp>
# Include <boost/assign/list_of.hpp>
# Include <boost/typeof. hpp>
# Include <boost/random. hpp>
# Include <boost \ Progress. hpp>
Using namespace boost;
Using namespace std;
Using namespace stdext;

Template <typename T>
Void fill_set (T & c)
{
Variate_generator <mt19937, uniform_int <> gen (mt19937 (), uniform_int <> (0,100 ));
For (int I = 0; I <10000; ++ I) // Insert 10 thousand Integers
C. insert (gen ());
}
Template <typename T>
Void test_perform ()
{
T c;
Cout <typeid (c). name () <endl;
{
Boost: progress_timer t;
Fill_set (c );
}
{
Boost: progress_timer t;
C. count (10 );
}
{
Boost: progress_timer t;
C. find (20 );
}
}

Int main ()
{
Test_perform <multiset <int> ();
// Test_perform Test_perform <unordered_multiset <int> ();
System ("pause ");
Return 0;
}

Advanced topics:
Internal data structure:
The unordered library uses the bucket to store elements. elements with the same hash value are placed in the same bucket, the number of buckets of the current hash container can be obtained using the member function bucket_count (). bucket_size () returns the number of elements in the bucket, for example:
Unordered_set <int> us = (list_of (1), 2, 3, 4 );
Cout <us. bucket_count () <endl;
For (int I = 0; I <us. bucket_count (); ++ I) // access each bucket
{Cout <us. bucket_size (I) <",";}
When a hash container contains a large amount of data, the number of elements in the bucket increases, causing access conflicts. To improve the performance of the hash container, the unordered library will automatically increase the number of buckets when inserting elements. You cannot specify the number of buckets directly, but you can use the constructor or rehash () the function specifies the minimum number of buckets. For example:
Unordered_set <int> us (100); // use 100 buckets to store data
Us. rehash (200); // use 200 buckets
The draft c ++ 0x RT1 also stipulates that there is a function max_load_factor (), which can obtain or set the maximum load factor of the hashed container, that is, the maximum average number of elements in the bucket, generally, the maximum load factor is 1. Users should not change it. It is meaningless if it is too large or too small.

Supported custom types:
The unordered Library supports c ++ built-in types and most standard library containers, but does not support custom types because it cannot calculate hash values of custom types.
To enable unordered to support custom types, you need to customize the second and third parameters of the class template, that is, for the hash function and equal comparison predicates.
Equal comparison predicates. the unordered library uses std: operator _to by default. This is a function object in the standard library. It uses operator =. Only the custom class can implement this operator, you do not have to write a function object. If you need a special equality judgment rule, you can write function objects and pass them to the unordered container.
Hash functions must be implemented. This is why they are placed before the template parameter list. We need to use boost. hash library to calculate the hash value of the custom type. A simple way to use a group is to compile a hash_value () function, create a hash function object, and then use its operator () returns the hash value.
The following code defines a class demo_class, which implements operator = and hash functions and can be accommodated by unordered:
# Include <iostream>
# Include <typeinfo>
# Include # Include <set>
# Include <boost/unordered_set.hpp>
# Include <boost/assign/list_of.hpp>
# Include <boost/typeof. hpp>
# Include <boost/random. hpp>
# Include <boost/Progress. hpp>
# Include <boost/functional/hash. hpp>
Using namespace boost;
Using namespace std;
Using namespace stdext;
Using namespace boost: assign;
Struct demo_class
{
Int;
Friend bool operator = (const demo_class & l, const demo_class & r)
{Return l. a = r. ;}
};
Size_t hash_value (demo_class & s)
{Return boost: hash <int> () (s. );}

Int main ()
{
Unordered_set <demo_class> us;
Demo_class a1;
A1.a = 100;
Cout Demo_class a2;
A2.a = 100;
Cout

System ("pause ");
Return 0;
}
Differences with TR1:
Boost. unordered is basically implemented based on the draft c ++ 0x standard, but it has a small "extension" that adds the comparison operators operator = and operator! =; Note: These two operators do not belong to the c ++ 0x standard. If the program is to switch to the new standard in the future, it may encounter the problem of unavailability of transplantation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.