C ++ review-standard library-map
For map, that is, Dictionary, kv key-value pair.
In C ++, It is a class template and belongs to an associated container class template.
template < class Key, // map::key_type class T, // map::mapped_type class Compare = less
, // map::key_compare class Alloc = allocator
> // map::allocator_type > class map;
When creating a map type, we must provide the Key and Value types. The comparator and provisioner are optional. Generally, the provisioner must be provided only when you use your own type.
In map, keys are unique and cannot have multiple identical keys. They are all sorted by Key size. That is to say, maps are automatically sorted,
The data in map is stored as pair.
typedef pair
value_type;
Common member variables:
Value_type; // pair
Iterator; // iterator, pointing to value_typeconst_iterator; // constant iterator reverse_iterator; // reverse iterator const_reverse_iterator; // constant, reverse
Common member functions:
// 1. iterator begin (); end (); rbegin (); rend (); cbegin (); // The following C ++ 11 is added to cend (); crbegin (); crend (); // all the above are returned iterators. In this example, the iterator starting with r indicates the reverse iterator, And the iterator starting with c indicates the const iterator. // 2. capacity: empty (); // test whether map is empty size (); // return the container size; // 3. obtain the element operator []; // It can be used in the same way as an ordinary array. At (const key_type & k); // The new addition method of C ++ 11. // 4. add, delete, modify, and query insert (const value_type & val); // Add erase (iterator position); // Delete size_type erase (const key_type & k ); // Delete void erase (iterator first, iterator last); // Delete clear (); // delete all data. Find (const key_type & k); // query count (const key_type & k); // It has a feature repeat with find because the key of map is unique, therefore, count can only return two values, 0 or 1, indicating that the key exists or does not exist.
A dictionary is a data structure that is frequently used in programming. For example, you sometimes need to calculate the number of times each word appears in an article to form the word vector of the article.
#include
#include
using namespace std;int main(){ string temp; map
word_count; cout<<"please input the word your want to count, and input the ctrl+D to end of the input"<
>temp) { cout<<"input word:"; // word_count[temp]++; // word_count.insert(pair
(temp,1); if( word_count.find(temp)==word_count.end()) { word_count.insert(pair
(temp,1)); } else { word_count[temp]++; } } int num_word=word_count.size(); cout<<"The number of word is:"<
::iterator itera; for(itera=word_count.begin();itera!=word_count.end();itera++) { cout<<"word: "<
first<<" occur"<
second<<" times"<