C ++ Primer study note _ 39_STL practice and Analysis (13) -- multimap and multiset

Source: Internet
Author: User

STL practice and analysis-multimap and multiset



Introduction:

In the map and set containers, a key can only correspond to one instance, while the multiset and multimap types allow a key to correspond to multiple instances.

The multimap and multiset types have the same header file definition as the corresponding single-element version: map and set header files.

The multimap/multiset type is the same as the map/set operation, with only one exception: multimap does not support subscript operations. In such containers, a key may correspond to multiple values.ThereforeMultimap/multisetFor a key, you must prepare for processing multiple values instead of a single value..


I. add and delete Elements

The insert and erase operations described earlier also apply to multimap and multiset containers. The difference is that keys are unique, so an element is always added when an insert operation is called.

    multimap<string,string> authors;    authors.insert(make_pair("Barth John","Sot-Weed Factor"));    authors.insert(make_pair("Barth John","Sot-Weed Factor"));

The erase version with a key parameter deletes all elements with the key,And return the number of deleted items.. The version with one or a pair of iterator parameters only deletes the specified Element and returns the void type:

    multimap<string,string> authors;    authors.insert(make_pair("Barth John","Sot-Weed Factor"));    authors.insert(make_pair("Barth John","Sot-Weed Factor"));    authors.insert(make_pair("Barth John","Sot-Weed Factor"));    string searchStr("Barth John");    multimap<string,string>::size_type cnt = authors.erase(searchStr);    cout << cnt << endl;//cnt == 3

2.MultimapAndMultisetSearching Element

The elements associated with the nap and set containers are stored in sequence, and the same is true for multimap and multiset. Therefore, in the multiset and multim containers, if a key corresponds to multiple instances, these instances must be stored adjacent to each other in the container.

Therefore, when traversing the multimap/multiset container, you can ensure that all elements associated with a specific key are returned in turn.


1. Use the find and count operations

You can use the count function to find the number of times a key appears, and the find operation returns an iterator,Point to the first instance with the key being searched:

    multimap<string,string> authors;    string first,second;    while (getline(cin,first))    {        getline(cin,second);        authors.insert(make_pair(first,second));    }    string search_item("Alain de Botton");    typedef multimap<string,string>::size_type sz_type;    sz_type entries = authors.count(search_item);    multimap<string,string>::iterator iter = authors.find(search_item);    for (sz_type cnt = 0;cnt != entries; ++cnt,++iter)    {        cout << iter -> second << endl;    }    cout << "First:\t\t\tSecond:" << endl;    for (multimap<string,string>::iterator iter = authors.begin(); iter != authors.end(); ++iter)    {        cout << iter -> first << "\t\t" << iter -> second << endl;    }

2. Unique iterator-oriented solutions

The operations listed in the following table apply to all associated containers. They can also be used for common map and set containers, but are more commonly used for multiamp and multiset containers. All these operations require a key and return an iterator.

Returns the associated container operation of the iterator.

M. lower_bound (k)

Returns an iterator pointing to a key not lessKThe first element

M. upper_bound (k)

Returns an iterator pointing to a key greaterKThe first element

M. Sort _range (k)

HisFirstMembers are equivalentM. lower_bound (k ),

SecondMembers are equivalentM. upper_bound (k)


Calling the lower_bound function and upper_bound function on the same key generates an iterator range, indicating all the elements associated with the key. If the key exists in the container, two different iterators will be obtained: The iterator returned by lower_bound points to the first instance associated with the key, the iterator returned by upper_bound points to the next position of the last instance. If the key is not in multimap, the two operations will return the same iterator,All pointThe same element or pointMultimapBeyond the end.

    typedef multimap<string,string>::iterator authors_it;    string searchVal = "Barth John";    authors_it beg = authors.lower_bound(searchVal),               end = authors.upper_bound(searchVal);    while (beg != end)    {        cout << beg -> second << endl;        ++ beg;    }

These two operations do not describe the existence of keys. The key is that the return value provides the iterator range.


3. performance_range Function

The upper_bound and lower_bound functions can be called by calling the performance_range function. The pai_range function returns the pair object that stores a pair of iterators. If this value exists, the first iterator in the pair object points to the first instance associated with the key, and the second iterator points to the next location of the last instance associated with the key. If no matching element is found, both iterators in the pair object will point to the location where the key should be inserted.

    pair<authors_it,authors_it> pos        = authors.equal_range(searchVal);    while (pos.first != pos.second)    {        cout << pos.first -> second << endl;        ++ pos.first;    }

// Appendix: unused typedef versions of the above two programs string searchVal = "Barth John"; multimap <string, string >:: iterator beg = authors. lower_bound (searchVal), end = authors. upper_bound (searchVal); cout <"First: \ t \ tSecond:" <endl; while (beg! = End) {cout <beg-> first <"\ t" <beg-> second <endl; ++ beg;} cout <endl; pair <multimap <string, string >:: iterator, multimap <string, string >:: iterator> pos = authors. performance_range (searchVal); while (pos. first! = Pos. second) {cout <pos. first-> first <"\ t" <pos. first-> second <endl; ++ pos. first ;}

// P325 exercise 10.26int main () {multimap <string, string> authors; ifstream inFile ("input"); string first, second; while (getline (inFile, first )) {getline (inFile, second); authors. insert (make_pair (first, second);} string eraseVal ("Barth John"); if (authors. find (eraseVal )! = Authors. end () {multimap <string, string >:: size_type cnt = authors. erase (eraseVal); cout <"Have erased" <cnt <"books" <endl ;} else {cout <"Have erased 0 book" <endl ;}}

// Exercise 10.27 multimap <string, string> authors; ifstream inFile ("input"); string first, second; while (getline (inFile, first) {getline (inFile, second); authors. insert (make_pair (first, second);} string eraseVal ("Barth John"); pair <multimap <string, string >:: iterator, multimap <string, string> :: iterator> pos = authors. performance_range (eraseVal); if (pos. first! = Pos. second) {authors. erase (pos. first, pos. second);} else {cout <"Have not found eraseVal" <eraseVal <endl ;}cout <"First: \ t \ tSecond:" <endl; for (multimap <string, string >:: iterator iter = authors. begin (); iter! = Authors. end (); ++ iter) {cout <iter-> first <"\ t" <iter-> second <endl ;}

// Exercise 10.28 This section is a very good exercise. It is worth carefully reading int main () {multimap <string, string> authors; string author, book; ifstream inFile ("input "); while (getline (inFile, author) {getline (inFile, book); authors. insert (make_pair (author, book);} multimap <string, string >:: iterator iter = authors. begin (); if (iter = authors. end () {cout <"map is empty" <endl; return 0 ;}/ * for (multimap <string, string >:: iterator it = authors. B Egin (); it! = Authors. end (); ++ it) {cout <it-> first <''<it-> second <endl;} */string currAuthor, preAuthor; do {currAuthor = iter-> first; if (preAuthor. empty () | currAuthor [0]! = PreAuthor [0]) {cout <"Author Names Beginning with" <currAuthor [0] <":" <endl ;} cout <"\ t" <currAuthor; pair <multimap <string, string >:: iterator, multimap <string, string >:: iterator> pos = authors. performance_range (currAuthor); while (pos. first! = Pos. second) {cout <',' <pos. first-> second; ++ (pos. first);} cout <endl; iter = pos. second; preAuthor = currAuthor;} while (iter! = Authors. end ());}

I got my first blog post after "experts" to commemorate O (∩ _ ∩) O Haha ~, This is the last blog dedicated to containers. Tomorrow, we will start our algorithm journey!

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.