The key word holds the element in order,Map, associative array, save keyword-value pairs, set, keyword is value, save only the keyword container multimap, the keyword can be repeated multiset, unordered collection unordered_map, with hash function organization Mapunordered_set, Setunordered_multimap organized with hash functions, hash organization map, keywords can be repeated unordered_multiset, hash organization set; keywords can recur
Usually a map is called an associative array, unlike an array whose subscripts do not have to be integers//count the number of occurrences of each word in the input map<string,size_t> word_count;string word;while (cin>> Word) ++word_count[word];for (const auto &w:word_count) cout<<w.first<< "occurs" <<w.second << (W.second>1) "Times": "Time" <<endl; define a map, we must specify the keyword and the worthwhile type. If Word is not yet in map, the following table operator creates a new element whose keyword is word, with a value of 0 when you extract an element from a map, you get a pair class object, and first holds the keyword
Ignore common words, save map<string,size_t> with set word_count;set<string> exclude = {"The", "but", "and", "Or", "an", "A", " The ', ' but ', ' and ', ' or ', ' an ', ' a '};string word;while (Cin>>word) if (Exclude.find (word) ==exclude.end ())// Only count words that are not in exclude ++word_count[word];
Associative containers support the basic operation of ordinary containers, and do not support the position-related operations of sequential containers, such as Push_front or push_back. The reason is that the elements in the associative container are stored according to the keyword, which is meaningless for the associative container. Also, constructors or insert operations are not supported. These accept an element value and a number of iterators that are worth manipulating the associated container are bidirectional, each associative container defines a default constructor that creates an empty container of the specified type. We can also initialize the associative container as a copy of another container of the same type, or initialize the associative container from a range, as long as the values can be converted to the type required by the container. Multimap or multiset allows multiple elements to have the same keyword.
We must define a comparison method for an ordered associative container. The default is to use < we can also provide our own operations, but must meet strict if required when two keywords are simultaneously associated with the same element, we can use any one of them to access the element bool Compareisbn (const sales_data &LHS, const Sales_data &rhs) {return LHS.ISBN () < RHS.ISBN ();} Multiset<sales_data,decltype (COMPAREISBN) *> Bookstore (COMPAREISBN); Here we use Decltype to get a pointer type for a function, you must add a * To indicate that we want to use a pointer to a given function. Initialize the bookstore object with COMPAREISBN, which means that when we want to bookstore add elements, by calling COMPAREISBN to sort the elements, you can use COMPAREISBN instead of & COMPAREISBN as a parameter to a constructor, because when we use a function name, it is automatically converted to a pointer when needed, and the effect is the same.
The pair is defined in the Uitlity header file. Operation on pair: PAIR<T1, t2> p; Initialize, respectively, the type of the member Pair<t1, t2> p (v1, v2);p air<t1, t2> p = {v1, V2};make_pair (V1,V2) returns a pair initialized with V1 and v2. The type of pair is inferred from V1 and v2 P.first p.second total data members two objects can be compared by using relational operators P1 relop P2 when P1.first <p2.first or! (P2.first < P2.first) && P1.second<p2.second founded P1<P2P1 = = P2 When first and second members are equal respectively, two pair is equal p1! = P2 Judging by = =
Imagine a function that needs to return a pair. Under the new standard, a list of return values can be initialized pair<string, int> process (vector<string> &v) {if (!v.empty ()) re Turn {v.back (), V.beck (). Size ()}; List initialization else return pair<string, int> (); Implicitly constructs return value}
We can also use Make_pair to return Make_pair (V.back (), V.back (). Size ()) or early methods: Return pair<string, Int> (V.back (), V.backe (). Size ());
Association container additional type name: type of key_type keyword Mapped_type the type associated with each keyword, only applies to mapvalue_type for set and Key_type, for map pair<const ke Y_type,mapped_type>set and map also have const and non-const versions of iterators that typically do not use generic algorithms for associative containers, the keyword is const, and we can use a read-only algorithm such as find. But not in a good idea, not keywords to do (fast) find. To use the version of the member function that you define, in real programming, if you are using an algorithm for an associative container, either as a source sequence or as a destination
Insert element: C.insert (v) v is an object of type value_type; args is used to construct an element c.emplace (args) for map and set, which can only be inserted if the element's keyword is not in C. The function returns a pair that contains an iterator. Points to the element that has the keyword, and a bool value that indicates whether the insertion succeeded. For Multimap and multiset, always insert the given element and return an iterator to the new element C.insert (b,e) B,e is an iterator that represents a C::value_type type worth the range; Il is a worthwhile initialization list. The function returns Voidc.insert (IL); For set and map, only the Insert keyword does not exist. For Multimap and Multiset, each element in the range is inserted in C.insert (P,V) similar to insert (v) (or emplace (args)) but with p to indicate where to start searching for new elements where they should be stored. Returns an iterator that points to the element of the given original word c.emplace (P,args)
Delete operation: C.erase (k) removes the element with each keyword K from c and returns a Size_type value. Indicates the number of deleted elements, if return 0 indicates the element to be deleted. C.erase (P) in the container removes the element specified by the iterator p from c. P must point to the true element in C and cannot be equal to C.end (). Returns an iterator to the element after P, and if p points to the tail element in C, returns C.end () C.erase (b,e) removes the elements in the range represented by Iterators B and E, and returns E
Because the subscript operator may insert a new element, we can only use subscript for a non-const map. Using a key that is no longer in the container as subscript, an element with this keyword is added to the map. C[k] c.at (k) access to the keyword k element, dai parameter check; if k is not in C, throw a Out_of_range exception. When a map is subscript, a Mapped_type object is obtained, and when the dereference is a map iterator, a Value_type object is obtained.
To find the operation of an element in an associative container: Lower_bound and Upper_bound are not suitable for unordered containers. Subscript and at operations only apply to non-const maps and Unordered_mapc.find (k) to return an iterator that points to the first element with the keyword K, and if K is not in the container, returns the number of elements that have the keyword equal to K, C.count (k). For containers that do not allow duplicate keywords, the return value is always 0 or 1c.lower_bound (k) returns an iterator that points to the element with the first keyword not less than k C.upper_bound (k) returns an iterator that points to the element with the first keyword greater than k C.equal_ Range (k) returns an iterator pair that represents the range of elements that are equal to K for the keyword. If K does not exist, the two members of pair equals c.end ()
If there are multiple elements in Multiset and multimap with the given keyword. Then these elements are stored adjacent to the container. String Search_item ("Alain de Botton"); Auto entries = Authors.count (search_item); auto iter = Authors.find (Search_item); while (entries) {cout<< iter->second<<endl; ++iter; --Entries;} When we traverse a multimap or multiset, we are guaranteed to get all the elements in the sequence with the given keyword
If the keyword is in the container, Lower_bound returns an iterator that points to the first element with the given keyword, and upper_bound returns an iterator that points to the position after the last element that matches the given keyword. Calling Lower_bound and upper_bound with the same keyword will give you an iterator range that means that all of the elements with that keyword can have a trailing iterator, and if the element we're looking for has the largest keyword in the container, then the keyword's upper_ Bound returns the post-tail iterator. If the keyword does not exist and is larger than any of the keywords in the container, then Lower_bound returns the trailing iterator. The iterator returned by Lower_bound may point to an element with the given keyword, but may also not point to. If the keyword is not in the container, Lower_bound returns the first safe insertion point for the keyword. Rewrite the previous program for (Auto Beg=authors.lower_bound (Search_item), End=authors.upper_bound (Serch_item); beg!=end;++beg) cout& lt;<beg->second<<endl; If no elements match the given keyword, lower_bound and upper_bound return an equal iterator that points to the insertion point of the given keyword.
Use Equa_range to modify our program again: for (auto Pos=authors.equal_range (search_item); Pos.first! = Pos.second; ++pos.first) cout<& lt;pos.first->second<<endl; Unordered associative containers use the = = operator of a hash function and a keyword type to organize elements, are unordered, are often simpler to use out-of-order containers, and have better performance if the keyword type is inherently unordered, or if the performance test finds that the problem can be solved with hashing techniques, you can use unordered containers in addition to the hash management operations. Unordered containers also provide the same operations as ordered containers (find, insert, and so on), which are used for map. Set functions can also be used for unordered_set and unordered_map, the same unordered container also has the multi_ version//rewrite the word count program, the only difference is the type of word_count, get the same result, That's not the same sequence. Unordered_map<string, size_t> word_count;string word;while (cin >> Word) ++word_count[word];fo R (Const auto &w:word_count) cout<<w.first<< "occurs" <<w.second<< ((w.secound>1)? " Times ":" Time ") <<endl;
Unordered container management operations: Bucket interface: C.bucket_count () Number of buckets in use C.max_bucket_count () the container can hold the maximum quantity of buckets c.bucket_size (n) How many elements are in the nth bucket C.buck Et_size (k) the element in which the key k is in which bucket the bucket iterates local_iterator the iterator type that can be used to access the elements in the bucket const_local_iterator the const version of the bucket iterator C.begin (n), C.E nd (n) bucket n first element and trailing iterator C.cbegin (n), C.cend (n) const version hash Policy c.load_factor () average number of elements per bucket, return float value c.max_load_factor () C tries to maintain the average bucket size, returning the float value. C adds a new bucket when needed so that Load_factor<=max_load_factorc.rehash (n) reorganizes the store so that Backet_count >= N and Backet_count>size/max_ Load_factorc.reserve (n) reorganizing the store. Allows C to save n elements without rehash
For unordered containers, they also define an object of type hash<key_type> to generate a hash value for each element. The standard library provides a hash template for built-in types, including pointers, and also defines hashes for some standard library types, including string and smart pointers. Therefore, you can define the unordered container directly However, we cannot directly define an unordered container with a keyword type of custom class type. Unlike a container, you cannot use a hash template directly, and you must provide your own version of the hash template instead of using the default method, we do not use a default comparison operation that is similar to adding an overloaded keyword to an ordered container. size_t hasher (const sales_data &SD) {return hash<string> () (SD.ISBN ());//Call Constructor}bool Eqop (const sales_data &A MP;LHS, const Sales_data &RHS) {return LHS.ISBN () = = RHS.ISBN ();} Using Sd_multiset = Unordered_multiset<sal Es_data, Decltype (hasher) *, Decltype (EQOP) *>sd_multiset Bookstore (42,HASHER,EQOP);
Of course, if our class defines = = We only overload the hash function on the line.
C++11 (10): Associative container