STL set, MAP, hash_map Learning

Source: Internet
Author: User

1. map function:

  1. Automatically create the corresponding key-value. Key and value can be any type you need.
  2. You can quickly search for records based on the key value. The search complexity is basically log (N). If there are 1000 records, you can search for up to 10 records, 1,000,000 records, and up to 20 records.
  3. Insert key-value records quickly.
  4. Quickly delete records
  5. Modify the value record based on the key.
  6. Traverse all records.

2. Use

# Include <map> // note that the STL header file does not have the extension. h.

Insert element: Two Methods

(1)

Enummap [1] = "one ";
Enummap [2] = "two ";

However, there is a performance problem. When inserting 2, search for the item with the primary key 2 in enummap. No

And then insert a new object into enummap. The key is 2 and the value is an empty string. After the insertion is complete, the string is assigned as "two "; this method assigns each value to the default value and then to the displayed value. If an element is a class object, the overhead is relatively large.

(2)

Enummap. insert (Map <int, cstring >:: value_type (2, "two "))

Delete element:

Erase () function

Iterator erase (iterator it); // delete an entry object

Iterator erase (iterator first, iterator last); // delete a range

Size_type erase (const key & Key); // Delete by using the keyword

The clear () function is equivalent:

Enummap. Erase (enummap. Begin (), enummap. End ());

Search for and obtain elements in Map

String STR = enummap [2];

3. Underlying Map

Map uses the red and black trees at the underlying layer,
For more details, see
http://www.cnblogs.com/zjfdlut/archive/2011/08/12/2135698.html   


4. hash_map
Based on the hash table, it provides faster access and query than map when the memory is sufficient.
For details, see:
http://www.cnblogs.com/yydy1983/archive/2010/03/04/1678195.html

5. Use hash_map in GCC

Because hash_map is not part of STL, although each c ++ compiler provides this container, it is still used differently.

For example, when using the GCC compiler in code blocks, you can

Usage:

Namespace std
{

Using namespace _ gnu_cxx;
}

#include 
Then
std::hash_map<int,int> hm;

For the hash_set of the User-Defined class, add your own compare and hash functions, for example, for the string
// Use the system-defined string hash function struct str_hash {size_t operator () (const string & Str) const {return _ stl_hash_string (Str. c_str () ;}}; // you can customize the hash function struct str_hash2 {size_t operator () (const string & Str) const {unsigned long _ H = 0; for (size_t I = 0; I <Str. size (); I ++) _ H = 5 * _ H + STR [I]; return size_t (_ H );}};

  


6Example
 
 
# Include <iostream> # include 

  

 
7. set
The underlying data structure is the same as that of map, which is a red-black tree with unique elements. In STL,
Use the set_intersection, set_union, set_difference, and set_symmetric_difference functions provided by algorithm,
It can easily implement the intersection, union, difference, and symmetry difference operations of a set, which is very powerful.
 
Set sorts the elements. The sorting rules are specified by compare. In fact, the standard form of set is set <key, compare, alloc>. Compare indicates a comparison function, which can be implemented through a class or struct.
Alloc is the set distributor. due to internal memory management, the following example sets the char x
 
Example:
# Include <set> # include <iterator> # include <iostream> # include <algorithm> using namespace STD; int main () {/* = */ set <int> eg1; // insert eg1.insert (1); eg1.insert (100); eg1.insert (5); eg1.insert (1); // element 1 does not insert 1eg1 again in the set because it already exists. insert (10); eg1.insert (9); // traverses the set and you can find that the element is an ordered set <int>: iterator set_iter = eg1.begin (); cout <"set named eg1:" <Endl; For (; set_iter! = Eg1.end (); set_iter ++) cout <* set_iter <""; cout <Endl; // use size () the function obtains the number of current elements. cout <"Now there are" <eg1.size () <"elements in the Set eg1" <Endl; If (eg1.find (200) = eg1.end () // The find () function can be used to check whether the element has cout <"200 isn' t in the Set eg1" <Endl; /* =============================================================*/Set <int> eg2; for (INT I = 6; I <15; I ++) eg2.insert (I); cout <"set named eg2:" <Endl; for (set_iter = eg2.begin (); set_iter! = Eg2.end (); set_iter ++) cout <* set_iter <""; cout <Endl; // obtain the union of two sets <int> eg3; cout <"union:"; set_union (eg1.begin (), eg1.end (), eg2.begin (), eg2.end (), insert_iterator <set <int> (eg3, eg3.begin (); // note the form of the fifth parameter copy (eg3.begin (), eg3.end (), ostream_iterator <int> (cout ,"")); cout <Endl; // get the intersection of two sets. Note that the Set receiving result before the set operation must call the clear () function to clear eg3.clear (); set_intersection (eg1.begin (), eg1.end (), eg2.begin (), eg2.end (), insert_iterator <set <int> (eg3, eg3.begin (); cout <"intersection :"; copy (eg3.begin (), eg3.end (), ostream_iterator <int> (cout, ""); cout <Endl; // get the eg3.clear () Difference between the two sets (); set_difference (eg1.begin (), eg1.end (), eg2.begin (), eg2.end (), insert_iterator <set <int> (eg3, eg3.begin (); cout <"difference: "; copy (eg3.begin (), eg3.end (), ostream_iterator <int> (cout," "); cout <Endl; // obtain the symmetry difference between the two sets, that is, if the two sets are A and B respectively, then the symmetry difference is AUB-A ∩ B eg3.clear (); set_symmetric_difference (eg1.begin (), eg1.end (), eg2.begin (), eg2.end (), insert_iterator <set <int> (eg3, eg3.begin (); copy (eg3.begin (), eg3.end (), ostream_iterator <int> (cout ,"")); cout <Endl; return 0 ;}

  

 
Of course, the more common application method is that the data type is also replaced by a user-defined class. Compared functions can be customized, or even two-level comparison can be added. For example, sorting by the total score first, sort by ID if scores are the same
 
Example:
 
#include<iostream>#include<iterator>#include<set>#include <algorithm>#include <string>#include <list>using namespace std;struct Entity{int id;int score;string name;};struct compare{        bool operator()(const Entity& e1,const Entity& e2)const   {                if(e1.score<e2.score) return true;                else                        if(e1.score==e2.score)                                if(e1.id<e2.id) return true;                return false;        }};int main(){        set<Entity,compare>s_test;        Entity a,b,c;        a.id=123;a.score=90;a.name="a";        b.id=121;b.score=85;b.name="b";        c.id=130;c.score=85;c.name="c";        s_test.insert(a);s_test.insert(b);s_test.insert(c);        set<Entity,compare>::iterator itr;        cout<<"Score List(ordered by score):\n";        for(itr=s_test.begin();itr!=s_test.end();itr++)                cout<<itr->id<<"---"<<itr->name<<"---"<<itr->score<<endl;        return 0;}

  

8 set STL source code is transferred from:
http://www.cnblogs.com/hustyangli/articles/1286302.html


Refer:
http://www.cnblogs.com/hustyangli/articles/1286302.html
http://apps.hi.baidu.com/share/detail/16186741

 
 
 

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.