C + + associative container knowledge summary

Source: Internet
Author: User
Tags map class

The container type of C + + can be divided into two categories: sequential container and associative container. The knowledge of sequential containers can be reviewed in my previous essay, "C + + sequential container knowledge summary". The correlation container supports the efficient search and reading of elements by key values, which is the biggest difference between it and the sequential container. The two basic types of associative containers are map and set. The elements of map are organized as key-value pairs: The key is used as the index of the element in the map, and the value represents the data that is stored and read. The set contains only one key and effectively supports queries about the existence of a key. The following table is the type of the associated container:

map                      associative array; the element uses keys to store and read                        sets of variable set sizes, enabling fast read by keys Multimap                 map types that support the same key multiple occurrences multiset                 a set type that supports multiple occurrences of the same key

A. Pair type

Before we begin to introduce the associative container, we need to understand a standard library type--pair type that is associated with it, which is defined in the header file utilty. The following table is the operation provided by the pair type.

pair<t1,t2>    p1;                     Create an empty pair object whose two elements are T1 and T2 types, with values initialized pair<T1,T2>    p1 (v1,v2);              Creates a pair object whose two elements are the T1 and T2 types, where the first member is initialized to the V2,second member and initialized to V2. Make_pair (V1,V2)                       creates a new pair object with v1,v2 values whose element types are v1,v2 type P1<p2                                  less than two pair objects, followed by dictionary order p1= = P2                                 If the first and second values of the two pair objects are equal in turn, they are equal P.first                                return a data member named first in P P.second                               returns a data member named second in P 

As you can see, the pair is a template type as well as a container. Its data members are public, named first and second, and can access their members with a single point of operation. Its definition of initialization is also very simple, in addition to the constructor, the pair also provides a make_pair function to create a pair object, and assign value to the existing pair object.

  

pair<string,string>    next_auth; string     first,last;  while (Cin>>first>> last)    next_auth=Make_pair (first,last); // The above assignment operation is equivalent to the following statement next_auth=pair<string,string> (first,last);
Two. Map type

Map is a collection of key-value pairs. The map type can be understood as an associative array: You can use the key as the subscript to get a value, just like the built-in array type. Associative containers such as map and set share the operations of most sequential containers. Associative containers do not provide front, Push_front, Pop_front, back, push_back, and pop_back operations.

Definition of 1.map objects

Before using the Map object, you need to include the map header in the header file. A sample definition is as follows:

#include <map>Map<string,int>  word_count;    

In addition, map has a total of 3 constructors for definition and initialization.

Map<k,v>    m;                 Create an empty map object named M with the key and value types K and V type map<k,v>    m (m2), respectively;             Create a copy of M2 M,m and M2 must have the same key and value type as map<k,v>    m (b,e);            Creates an object m of the map type that stores a copy of all the elements in the scope of the iterator B and e tags. The type of the element must be able to convert bits pair<const k,v>

  

Types of 2.MAP definitions

Because the elements of the map object are key-value pairs, each element contains two parts: The key and the value associated by the key. Vaule_type is the key for storing elements as well as the pair type, and the keyed const. The following table defines the types for the map class.

Map<k,v>:: Key_type               in the map container, the type of the key used as the index map<K,V>:: Mapped_type            in the map container, The type of the value associated with the key is map<k,v>::value_type             a pair type. Its first element has a const map<k,v>::key_type type, while the second element has a map<k,v>::mapped_type type

Note that referencing the map iterator will result in an object of type pair, whose first member holds the key and holds the value for the Const,second member.

Adding elements in 3.map

There are two ways to add elements to a map: one is to use the Insert member implementation. The second is to use the subscript to get the element, and then assign a value to the acquired element.

Map uses subscripts similar to vectors, and returns the values associated with the subscript, but the map subscript is a key instead of an incremented number. The following procedure is a good illustration of this feature.

map<string,int>    word_count;word_count["Anna" ]=1;

First find the element in Word_count that has the key for Anna, not found. A new key-value pair is then inserted into the Word_count container, the key is Anna, the value is initialized to 0, and the value 1 is assigned to the element that the key is Anna. As we can see, using subscripts to access elements that do not exist in the map causes a new element to be added to the map container, and its key is the subscript value. The subscript operation of Map is the same as the vector subscript operation: Returns the value associated with the key. Using these features of the map container, you can make the programming very concise. Examples of how many occurrences of each word are recorded as follows:

map<string,int>    word_count; string     Word; // Count The number of occurrences of a word in Word_count  while (cin>>word)     ++word_count;

The insert for the map container uses the pair type parameter. The following table provides the insert operation for the map container.

  

M.insert (E)              E is a value of type Vaule_type that is used on M. If the key e.first is not in M, an element with a key of E.first value of E.seconde is inserted. If the key already exists in M. Then M remains unchanged.                         The function returns an object of type pair that contains a map iterator to the element with the key E.first, and an object of type bool that indicates whether the insert succeeded. M.insert (beg,end)        Beg and end are iterators that mark the scope of an element, where the element must be a key -value pair of the M.value_type type .                         for a well-known element within the range, if its key does not exist in M, the key and its associated value are inserted into M. The return void    M.insert (iter,e)         E is a value that is used in the Vaule_type type. If the key is not in M, a new element is created and the location of the new element store is searched with the iterator ITER as the starting point.                         returns an iterator that points to an element in M with the given key. 

As follows:

//Method OneWord_count.insert (map<string,int>::value_type ("Anna",1));//method Two, using Make_pairWord_count.inser (Make_pair ("Anna",1));//method Three, using typedeftypedef map<string,int>:: Value_type valtype;word_count.insert (ValType ("Anna",1));

Find and read elements in 4.map

The disadvantage of reading elements in map is that they are added automatically when the element is not present, and sometimes this is something we don't want to see. So the map provides two additional operations: Count and find, which checks to see if a key exists without inserting the key.

M.count (k)               returns the number of K occurrences in M m.find (k)                if an element in the M container is indexed by K, the iterator that points to that element is returned. Returns an out-of-end iterator if it does not exist

The return value of the count member can only be 0 or 1, because the map value allows one key to correspond to one instance. If the return value is not 0, you can use the subscript operation to get the value associated with the key.

int occurs=0; if (Word_count.count ("foobar"))    occurs=word_count["foobar "];

Find operates an iterator that points to an element, and returns an end iterator if the element does not exist.

int  occurs=0; map<string,int>::iterator  it=word_count.find (" Foobar " ); if (it!=word_count.end ())    occurs=it->second;
deleting elements in 5.map

Deleting an element from the map container uses the erase operation, which has three variations, as follows:

M.erase (k)                removes the element with the M middle key as K. Returns a value of type Size_type that represents the number of deleted elements M.srase (p) Removes the element that the                iterator p points to from M. P must point to an element that does exist in M and cannot be equal to M.end (). The return void type m.erase (b,e)              removes a range of elements from M, which is marked by iterators on B and E. B and E must mark a valid range in M: that is, B and E must point to the element in M or the next position of the last element                          , and b either in E's money main, or equal to E. return void
Iterative traversal of 6.map objects

Map and other containers provide begin and end operations as well.

map<string,int>::const_iterator   map_it=word_count.begin ();  while (map_it!=word_count.end ()) {    cout<<map_it->first<<"occurs"             <<map_it->second<<"time"<<Endl;      + +map_it;}
Three. Set type

Set is just a collection of simple keys. Using the Set container is most appropriate when you want to know only if a value exists. The Set container supports most map operations, including constructors, inserts, Count, find, erase operations. However, the Mapped_type type is not defined except for subscript operations. Value_type is not a pair type in the set container, but is the same type as Key_type. As with map, the keys stored in the Set container are unique.

Definition and use of 1.set

You must include the set header file before using set, and the set supports operations that are basically the same as the map provides.

vector<int > ivec;  for (vector<int>::size_type  i=0; i!=; + +i) {    ivec.push_back (i);    Ivec.push_back (i);} // Initialize set with Ivec set<int>  iset (Ivec.begin (), Ivec.end ()), cout<<ivec.size () < <endl;        // outputcout<<iset.size () <<end;         // Output Ten    

2. Adding elements to set

  

// method One, insert directly Set<string>  set1;set1.insert ("the");     // method Two, using iterators Set<string>  set2;set2.insert (Ivec.begin (), Ivec.end ());
3. Getting elements from set

Set has no subscript operation, you can use the find operation in order to get the element from the set by key. If you are only judging whether an element exists, you can also use the count operation, and the return value can be only 1 or 0.

C + + associative container knowledge summary

Related Article

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.