The use method of map and Hash_map in C + + standard library

Source: Internet
Author: User
Introduction to the common operation of STL map

1. Introduction to Directory map features use map to insert elements in a map to find and get elements from a map to remove elements from a map

2. Map Introduction

Map is a kind of associative container. It is characterized by the addition and deletion of the node to the iterator is very small, in addition to that Operation node, the other nodes have no effect. For iterators, you can modify the real value instead of modifying the key.

3. The function of map automatically establishes key-value correspondence. The key and value can be any type you want. Quickly find records based on key values, find the complexity of the basic log (N), if there are 1000 records, find up to 10 times, 1,000,000 records, up to 20 times. Quickly insert Key-value Records. The quick Delete record modifies the value record according to key. Traverse all records.

4. Using Map

Use map to include the header file where the map class resides
#include <map>/Note that the STL header file does not have an extension. h

The map object is a template class that requires two template parameters for keywords and storage objects:
Std:map<int, string> personnel;
This defines an int as an index and has an associated pointer to a string.

For ease of use, you can do a type definition of the template class,

typedef map<int, cstring> udt_map_int_cstring;
Udt_map_int_cstring Enummap;

5. Inserting elements in a map

Changing the entry in the map is very simple because the map class has overloaded the [] operator

ENUMMAP[1] = "one";
ENUMMAP[2] = "two";
.....

This is very intuitive, but there is a problem with performance. Insert 2 o'clock, first in the Enummap to find the primary key of 2, not found, and then insert a new object into the Enummap, the key is 2, the value is an empty string, after the insertion is completed, the string is assigned to "two"; This method assigns each value to its default value and then assigns it to the displayed value, which is more expensive if the element is a class object. We can avoid overhead in the following ways:

Enummap.insert (Map<int, cstring>:: Value_type (2, "two"))

6. Find and get elements in a map

The subscript operator gives the simplest way to get a value:

CString tmp = enummap[2];

However, only when an instance of this key is available in the map, an instance is automatically inserted, with the value initialized.

We can use the find () and count () methods to discover whether a key exists.

Look for a key entry in the map with the Find () method, the incoming parameter is the key to look for, where you need to refer to the two members of Begin () and end () representing the first and last entries in the Map object, which are of type iterator.

int nfindkey = 2; Key to look for
Define an entry variable (actually a pointer)
Udt_map_int_cstring::iterator it= Enummap.find (Nfindkey);
if (it = = Enummap.end ()) {
Didn't find
}
else {
Found it
}

The iterator data type obtained through the method of the Map object is an std::p air object, including two data iterator->first and iterator->second representing keywords and stored data respectively

7. Remove an element from the map

Remove an item from a map with erase ()

The member method is defined as iterator erase (iterator it);        Deletes iterator erase (iterator, iterator last) by an entry object; Deletes a range Size_type erase (const key& Key); Delete by keyword

Clear () is equivalent to Enummap.erase (Enummap.begin (), Enummap.end ());

Introduction to STL hash_map

The use of Hash_map is the same as that of map, which provides operations such as Insert,size,count, and the elements inside are also stored in pair types. Although the externally provided functions and data types are consistent, but the underlying implementation is completely different, the map of the underlying data structure is rb_tree, and Hansh_map is a hash table to achieve.

void Main ()
{//Simple one, the use of the same method and map is the same.
Hash_map<int,string> hmap;//defines an instance
Hmap.insert (pair<int,string>, "SFSFD"))//Insert a pair object,

Hmap.insert (Hash_map<int,string>::value_type, "SDDSF");//value_type is pair type.


HMAP[23] = "23";
HMAP[33] = "33";
HMAP[-1] = "-1";
Hash_map<int,string>::iterator it = Hmap.begin ();
while (It!=hmap.end ())//traversal
cout<<it->first<< "T" <<it++->second<<endl;
it = Hmap.find (23);//Find
if (It!=hmap.end ())
PRINT (IT);
Cout<Cout<Cout<Hash_map<int,string>::const_reverse_iterator cit = hmap.rend ();
PRINT (CIT);
}

From the above, you can see that the use of it is no difficulty, very convenient. But when do we use map and when do we use Hash_map?

Map and Hash_map

Overall, the Hash_map lookup speed is faster than the map, and the lookup speed is independent of the size of the data, which is a constant level, and the lookup speed of the map is log (n) level. Hash also has a hash function that is time-consuming. When there are 100w records, the map only needs to compare 20 times, and 200w only needs 21 times. So it's not necessarily that the constant is smaller than log (n).

HASH_MAP Requirements for space is much higher than map, so it is a way to change time in space, and, hash_map if the hash function and hash factor selection is not good, you may not achieve the desired effect, so as to use map, or HASH_MAP, from 3 aspects to weigh: Find speed, amount of data, memory usage, and one is your experience. No special criteria.

In addition, you can rewrite the hash_compair to change the definition of bucket quantity inside, if the value is appropriate, you can get better performance. And if your data is a custom type, you'll have to rewrite the copy function. Can imitate the original writing, all the member functions, member variable one can not be less.

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.