Brief introduction of C++map type

Source: Internet
Author: User
One: Map's past and present life

(1) from the associative container and the sequential container, the associative container stores and reads the elements through key (key), while the sequential container stores and accesses the elements (vector,queue,stack,list, etc.) through the position order of the elements in the container.

The associative container (associative containers) supports the use of keys to efficiently find and read elements. The two basic associative container types are map and set. Where the elements of a map are organized in the form of key-value (Key-value) Pairs: The key is used as the index of the element in the map, while the value represents the data that is stored and read. The set contains only one key and effectively supports queries about whether a key exists.

(2) associated container type


The standard library provides 8 associated containers, as shown in the following table.

Ordered containers: type map and Multimap defined in header file map, set and multiset defined in header file set; unordered container: defined in Unordered_map and unordered_set respectively.

1--Description: The map type is often referred to as an associative array (associative array), the associative array and the normal array are similar to "normal" arrays, except that their subscripts do not have to be integers. We look for values by a keyword instead of a location. By contrast, set is a simple collection of keywords, and set is most useful when you just want to know if a value exists.

2--using Map

Statistics the number of each word input
map<string,size_t> word_count;    String to size_t empty map
string word;
while (CIN >> word)
	++word_count[word];        Extract Word's counter and add it to 1

3--using Set

Map<string,size_t> Word_count;      String to size_t empty map
set<string> exclude = {"The", "But", "and", "Or", "an", "A", "Then",
"the", "But", " and "," or "," an "," a "," then "};
string Word;
while (CIN >> Word)
	//statistics only for words not in exclude
	If (exclude.find (word) = = Exclude.end ())
	++word_count[ Word];        Extract Word's counter and add it to 1
4--

Note: The associated container has some restrictions on its keyword type. By default, the standard library uses the < operator of a keyword type to compare two keywords.

Pair type

Before introducing the associative container operation, we need to understand the standard library type named pair, which is defined in the header file utility. A pair saves two data members, first and second
(3) In general, if you want to effectively store a collection of different values, it is appropriate to use a set container, andThe map container is more appropriate for situations where you need to store (and even modify) the values associated with each keywhen you do some text processing, you can use the set to save words that you want to ignore. And the dictionary is a good application of map.: The word itself is a key, and its explanatory note is a value. Objects of set and map types contain elements that have different keys and do not allow a second element to be added to the same key.if a key must correspond to multiple instances, use either Multimap or multi set, which allows multiple elements to have the same key.

II: Map Introduction (official profile)


(1) Map is a kind of associative container, it is a template class. The essence of an association is that the value of an element is associated with a particular key, not by the position class of the element in the array. It is characterized by the addition and deletion of the node has little impact on the iterator, in addition to the operation of the node, the other nodes have no effect. For iterators, the key value cannot be modified, only its corresponding real value can be modified.

(2) The function of map
Automatic establishment of key-value correspondence. Key and value can be any type you want, but note that the only constraint on the type of key is the need to support the < operator.
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, quickly delete records, modify Value records according to Key, and traverse all records.

(3) Definition of 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, and the basic definition pattern is as follows:
Std:map<int, string> personnel;
This defines a map object personnel with the int as the key and the value as String.

The following three types are defined in the map:
Map<k, V>::key_type: Represents the type of index in the map container;
Map<k, V>::mapped_type: Represents the type of value associated with a key in the map container;
Map<k, V>::value_type: Represents a pair type whose the one has a const map<k, a V>::key_type type, and a second element with Map<k, V>: Mapped_type type
When you dereference an iterator, you get a reference to a Value_type type value in the container, and the value_type is the pair type for the map container.

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;

Three: Add elements to the map
There are two main ways to add elements to a map:
(1) Use the subscript operator to get the element, and then assign the element
For example:
Map<string, int> Word_count; Defines an empty map object Word_count;
word_count["Anna"] = 1;

Program Description:
1. Find the element of Anna in Word_count, not found.
2. Insert a new key-value pair into Word_count, his key is a const string object, save Anna. And his value is directly initialized, which means that in this case the middle finger is 0.
3. Insert this new key-value pair into the Word_count
4. Read the newly inserted element and assign her value to 1.
Using subscript to access a map is quite different from using subscript to access an array or vector: using subscript to access a nonexistent element will result in a new element being added to the map container, whose key is the subscript value.

(2) Adding elements using the Map::insert method
The insert operation provided by the map container:
1. Map.insert (E): E is a value_type type value used in the map. If the key does not exist, insert a new element with a value of E.second, and if the key already exists in the map, no action is taken. The function returns a pair type, the pair type's primary element is the map iterator that is currently inserting e, and the second type of the pair is a bool type indicating whether the element was inserted.
2. Map.insert (Beg, end): Beg and End are iterators, return void type
3. Map.insert (ITER, E): E is a value_type type value, if E.first is not in the map, creates a new element, searches for the location of the new element's storage with the iterator ITER, and returns an iterator that points to the element in the map with the given key.
For example:
Word_count.insert (map<sting, Int>::value_type ("Anna", 1));
Word_count.insert (Make_pair ("Anna", 1));
Return value: If the key is already in the container, its associated value remains unchanged and the bool value returned is true.

(3) Find and get the elements in the map

There is a dangerous side effect of using subscript to get an element: If the key is not in the map container, the subscript operation inserts a new element with that key.
Therefore, the query operation of the Map object is introduced:
Map.count (k): Returns the number of key K occurrences in the map (for map, because a key corresponds to a value, so returns only 0 and 1, so you can use this function to determine whether K is in map)
Map.find (k): Returns an iterator that points to the key k in the map, and returns out of the end iterator if there is no key K.

For example:
int occurs = 0;
if (Word_count.cout ("Foobar"))
Occurs = word_count["Foobar"];
int occurs = 0;
Map<string, Int>::iterator it = Word_count.find ("Foobar");
if (it!= word_count.end ())
Occurs = it->second;

(4) Removing elements from the map
Remove an item from a map with erase ()
The member method is defined as follows:
Iterator Erase (iterator it); Delete through an Entry object
Iterator Erase (iterator, iterator last); Delete a range
Size_type Erase (const key& Key); Delete by keyword

(5) iterative traversal of a map object

Like other containers, map provides the begin and end operations to generate iterators for traversing the entire container.

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.