C + + container (Associative container)

Source: Internet
Author: User

The essential difference between an associative container and a sequential container is that the associative container stores and accesses elements through key access and reading elements, sequential containers in the order in which the elements are placed in the container. Therefore, the associative container does not provide front, Push_front, Pop_front, back, Push_back, and Pop_back, and the associated container cannot be defined by the container size, because it will not be possible to know what the value of the key corresponds to.

The two basic associative container types 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. Set and Map type objects do not allow the second element to be added for the same key. If a key must correspond to more than one instance, use the Multimap or Mutiset type, both of which allow multiple elements to have the same key.

Before you introduce the associated container, you must first describe a simple standard library type--pair type that is related to it:

The initialization of the pair type-------in the header file utility

Pair<t1,t2> P1; Create a pair object, the type of the two elements is the T1,T2 type, initialized with the initial value

pair<t1,t2> P1 (V1,V2); Create a pair object, the type of two elements is the t1,t2 type, respectively, with V1,V2 initialization

Make_pair (V1,V2); Create a pair object with V1, v2, type V1, v2 type, respectively

P.first returns the first public data member in P

P.second returns the second public data member in P

Pair use:

#include <utility>
Pair<string,int> author ("Peter", 30);
cout<<author.first<< "\ t" <<author.second<<endl;//direct access to data members

using typedef for simplification
typedef pair<string,string> Student;
Student s1,s2 ("AAA", "BBB");
S1.first= "CCC";
S1.second= "DDD";

Use the Make_pair function to generate a new pair object
String first= "Eee", second= "FFF";
Student S3=make_pair (First,second);

Map associative array, stored and read by key

Map initialization:

Map<k,v> M1 creates an empty map of the name M to the image, the type of its keys and values are K, V, respectively

Map<k, v> m (m2) create a copy of M2 m,m and the type of the M2 must be the same as the key value type and value type

Map<k,v> m (b,e) creates an object m of the map type, stores a copy of all the elements in the iterator B and e tag ranges, the type of the element must be converted to Pair<const K, v>

Type of map definition :

Map<k,v>::key_type type of key to be indexed in map

Map<k,v>::mapped_type the type of the value associated with the key in the map

Map<k,v>::value_type a pair type whose first element has a const map<k,v>::key::type type, while the second element is Map<k,v>:: Mapped_type type

A map iterator that is dereferenced will produce an object of type pair, such as:

Map<string,int>::iterator map_it = Word_count.begin ();
cout<<map_it->first<< "" <<map_it->second<<endl;

To add a member to a map:

Use subscript to access the Map object: The Map object looks for an element whose key value is x if found, returns its value (type is Map<k,v>::mapped_type), otherwise inserts a new object key value of x, and a value of map<k,v> in V in default. Therefore, using subscript to access a map is different from using subscript to access an array or vector, and using subscript to access a nonexistent element will result in a new element being added to the map container, which is the subscript value. This feature allows the program to be concise:

Map<string,int> Word_count;
word_count["Peter"]=10;//equivalent to adding a key-value pair
Create a Map object to record the number of occurrences of each word, which is very concise.

Because if you are reading a new word, a new element with the word index will be added to the Word_count
Map<string,int> Word_count;
string Word;
while (Cin>>word)
{
++word_count[word];
}

To insert a map using insert:

M. Insert (E) e is a value of type value_type on M, and if E.first is not in M, a new element with a value of. Second is inserted, otherwise the key value already exists in M and remains unchanged, the

The function returns a new pair type that contains a map iterator that points to an element with a key value of E.first, and an object of type bool that indicates whether the element is inserted

M.insert (beg,end) inserts an element in the range of beg, end tags, or inserts if the M.first of the element already exists. return void type

M.insert (iter,e) If E.first is not in M, creates a new element and searches for the storage location of the new element with the iterator ITER, otherwise returns an iterator that points to the element with the given key in M.

Rewrite the word count program with the Insert method

Map<string,int> Word_count;
Word_count.insert (Map<string,int>::value_type ("AAA", 1));
Map<string,int> Word_count;
string Word;
while (Cin>>word)
{
Pair<map<string,int>::iterator,bool> Ret=word_count.insert (make_pair<string,int> (word,1));
if (!ret.second)//If not successfully inserted, prove that there is already a key value, the statistic value +1
{
++ret.first->second;//first is an iterator that points to the inserted key
}
}

To find and read elements in a map:

M.count (k) returns the number of times K appears in M, and only returns 0, 1 in map

M.find (k) returns the corresponding iterator if K is present in the key value in M, otherwise it returns out of the end iterator

Reading an element without inserting a new element
int occurs;
Map<string,int>::iterator it= word_count.find ("Foobar");//does not exist, returns an end iterator
if (It!=word_count.end ())//may not be found
{
Occurs=it.second;
}

Deleting an element from a map uses the same erase as the sequential container function:

M.erase (k) removes the element with the M middle key as K. The return value is the number of deleted elements, and the value of the map container must be 0 or 1.

M.erase (p) Removes the element that the iterator p points to from M. The return value is of type void.

M.erase (b,e) removes an element from M that is a range of iterators. The return value is of type void.

Iteration traversal of the Map object:

Map<string,int> Word_count;

Map<string,int>::const_iterator iter = Word_count.begin ();
while (Iter!=word_count.end ())
{
cout<<iter->second<<endl;
iter++;
}

Set type

The function of set is to sort. The value of each element cannot be changed directly. It is a container for storing data and for extracting data from a collection of data. Its value must be unique for each element, and the system will automatically sort the data based on that value. The value of each element cannot be changed directly.

A variable-sized collection that supports fast reads through key values. The set container is most suitable for simply wondering if a value exists

In the Set container, Value_type is not a pair type, but is the same as the type of key_value, and its key value type is unique and cannot be modified

Find, Count, insert, erase operations are also supported in set

Add elements to set:;

Set<int> Set1;
Pair<set<int>::iterator,bool> P=set1.insert (1);//Returns a pair type object that contains an iterator and a Boolean value
Set1.insert (2);
int arr[]={1,2,3};
Set<int> Set2;
Set2.insert (arr,arr+3);//return void type

Get elements from set: Similar to the map method, use the Find and count functions.

C + + container (Associative 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.