How to associate a set, multiset, map, and multimap container instance in C ++

Source: Internet
Author: User
Tags bool

Test Environment: windows 7 vs2010

The internal elements are arranged in an orderly manner. The insert position of the new element depends on its value and the search speed is fast.

In addition to functions available in various containers, the following member functions are also supported:

Find: find the elements that are equal to a specific value (if x is less than y and y is less than x, it is not equal immediately)
Lower_bound: find a lower bound
Upper_bound: searches for an upper bound.
Performance_range: searches for both the upper and lower bounds.
Count: calculates the number of elements equal to a certain value (if x is smaller than y and y is smaller than x, it is not equal immediately)
Insert: used to insert an element or interval.

Before learning to associate containers, we must first learn the pair template. The pair template is in the struct format, so its internal members are all public by default.

Template <class _ T1, class _ T2> // Two types of parameters, struct pair {typedef _ T1 first_type; // _ T1, are defined as first_type, _ T2 is defined as second_type typedef _ T2 second_type; _ T1 first; // first is _ T1 type _ T2 second; // seconde is _ T2 type pair (): first (), second () {}// nonargument constructor pair (const _ T1 & _ a, const _ T2 & _ B): first (_ ), second (_ B) {}// use _ a to initialize first ,__ B to initialize second template <class _ U1, class _ U2> // This is a template function constructor. It uses a pair object to initialize the first and second pair objects (const pair <_ U1, _ U2> & _ p): first (_ p. first), second (_ p. second ){}};


It is worth noting that the map/multimap containers store pair objects in ascending order of the first member variables.

Third constructor instance

Pair <int, int> p (pair <double, double> (5.5, 4.6); // p. first = 5, p. second = 4


Next let's take a look at set and multiset (the difference between set and multiset is that set does not allow duplicate key values)

Template <class Key, class Pred = less <Key>, class A = allocator <Key> class multiset {...... };


Variables of the Pred type determine how the elements in the multiset are defined as "one is smaller than the other. During the multiset operation, compare the size of the two elements x and y to generate a Pred type variable, which is assumed to be op. If the expression op (x, y) returns true, x is smaller than y.
The default Pred type is less <Key>.

Template <class T> structless: public binary_function <T, T, bool> {bool operator () (const T & x, const T & y) const {return x <y ;}};


// The less template compares the size by <. Therefore, when the key is a class, the class must be overloaded.


# Include <iostream> # include <set> using namespace std; void main () {set <int>: iterator setIter; pair <set <int>: iterator, set <int >:: iterator> mypair; pair <set <int >:: iterator, bool> result; set <int> myset; for (int I = 0; I <10; I ++) {myset. insert (I);} result = myset. insert (3); // set insert returns the pair object while multiset returns the iterator if (! Result. second) {cout <"3 already exists" <endl;} setIter = myset. find (2); // The find function returns the iterator if (setIter! = Myset. end () {cout <* setIter <endl;} else {cout <"not find" <endl;} mypair = myset. performance_range (4); // Obtain lower_bound and upper_bound cout <"lower_bound:" <* mypair. first <endl; cout <"upper_bound:" <* mypair. second <endl; for (setIter = myset. begin (); setIter! = Myset. end ();) {if (* setIter % 2 = 0) // delete an even number {setIter = myset. erase (setIter);} else {setIter ++;} cout <"after deleting an even number" <endl; for (setIter = myset. begin (); setIter! = Myset. end (); setIter ++) {cout <* setIter <endl;} cin. get ();}




In map/multimap, all objects in the pair template class are placed and sorted by the first class from small to large. The keys in the map cannot be repeated.

Multimap template <classKey, class T, class Pred = less <Key>, class A = allocator <T> class multimap {.... Typedefpair <const Key, T> value_type ;....... }; // Key indicates the type of the keyword



Elements in multimap are composed of <keywords, values>. Each element is a pair object, and the keyword is the first member variable. Its type is Key.
The keywords of many elements are the same in multimap. Elements are arranged from small to large according to the first member variables. By default, less <Key> is used to define the "less than" relationship of keywords.

# Include <iostream> # include <map> using namespace std; void main () {map <int, string> stu_name; // number name, which is sorted by number. It is a key-value pair map <int, string >:: iterator mapIter; stu_name.insert (map <int, string >:: value_type (1, "zhang san"); stu_name.insert (map <int, string >:: value_type (2, "li si"); stu_name.insert (make_pair (3, "wang er"); // use make_pair and mapIter = stu_name.find (2); // if (mapIter! = Stu_name.end () {cout <mapIter-> second. c_str () <endl;} else {cout <"not find" <endl;} for (mapIter = stu_name.begin (); mapIter! = Stu_name.end (); mapIter ++) {cout <mapIter-> first <":" <mapIter-> second. c_str () <endl;} cin. get ();}






Associated container: set multiset map multimap comparison

I,
1) set can only be a single value. It stores non-duplicate elements and cannot have two identical elements. You can use pair <set <int >:: iterator, bool> ret; key-value pairs to determine whether the two elements are the same;
If (ret. second = false) it = ret. first; can be used to determine whether a failure has occurred; * (ret. fisrt) can be used to obtain the same value.
2) the element value of set is its key value. While map has key and value
3) set will sort the elements in sequence.
 
II,
1) multiset can store the same elements.
2) insert returns the iterator.
3) Other
 
III,
1) map storage elements are formatted key and value values. Map is a special set. All its elements are pair <key, value>. The biggest feature of map is that map provides the ability to perform subscript operations on subscripts, you can operate map [key] like an array to reference the corresponding value.
2) you can find the keyword based on the key. Almost all map operations are key-based. For example, sort by comparing keys.
3) stores data in a tree structure, so the search time is short.
4) The key is unique and not synchronized. Each element has a key-value pair.
5) It is also ordered.
 
IV,
Multimap features; map cannot have duplicate key-value pairs. That is, if a key-value pair with the same key is inserted, the key-value pairs with the same key value will be overwritten.
Multimap will not overwrite.

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.