C + + Intermediate STL Basic Learning (II.)

Source: Internet
Author: User
Tags repetition

deque and vector, can be inserted in the front end of the back end, generally with deque instead of Vector,vector can only insert push_back () in the back end. Deque can also be Push_front (). List: Doubly linked list, cannot use subscript, and array vector deque different. You can only use iterators to indicate elements. Push_front,push_back,insert (position, value), where the position is typically specified by an iterator, where insert returns an iterator. For example Lis.insert (A.begin, A); Returns an iterator. Remove using erase (location), or erase (where A is, where b), where a is included, and B is not. Iterator and iterator range Iter.begin is the first one, Iter.end is the last one, and the real end is the last one, so begin ()=end (), the container is empty. Iter+n only vectors and deque can have this kind of operation. List is not available. The iterator is a pointer, so const_iterator is the value that the iterator points to does not change. Often iterators are used as iterations of a For loop, which is equivalent to a for (intI=0I in the;). Stack (container adapter) Stack,lifo form. You can use the deque (default) vector list to make stacks, stack<int, deque<int>>S. There is empty () size () Pop () Top () push (item);p Ush and pop are always pointing to the top of the stack. P.pop is to delete the data, not to return the deleted value, P.top () to view and return the viewed value. Queue (container adapter) (Stacks and queues do not have iterators, because they can no longer manipulate data, only at both ends, so the intermediate data cannot be modified) queue, FIFO, queue cannot be queued with vectors (because the requirement must operate on both sides, FIFO). such as queue<int, list<int>> Q; or designated as deque<int>(default is Deque). Operation, Q.empty (); Q.size (); Q.front (); View Team head, Q.back (); View Team tail, Q.pop (); Q.push (item);p Ush is at the end of the team, Pop is in the first line of operations. Priority Queue (container adapter) Priority_queue cannot use list, there is a maximum minimum priority queue. Priority_queue<int, deque<int>> PQ, or you can use Deque,vector (default =), you cannot use list. Pq.push (item), always sorted sequentially (maximum (default), or lowest value sort). Pq.size (); Gets the number of size data. Pq.top (); view, Pq.pop (); Delete, because the queue always points to the first team, so each deletion is the largest (minimum value). Pq.empty (); Determines whether it is empty. Use the least-value priority queue priority_queue<int,deque<int, greater<int>> PQ; keyword greater<int>indicates the priority queue for the minimum value. Sequential containers and container adapters vector list Deque;stack queue priority_queue (priority queue) initialization problems use the default constructor, which assigns values between different containers with parameter constructors, which can be implemented using iterators. Vector<int> Ivec (IVEC0); Use the same type of sequential container ivec0 initialize Ivec, where ivec0 must be vector<int>type. But List<string>slist (Svec.begin (), Svec.end ()); You can use iterators to assign values to different containers, such as Svec vector<string> type. Svec.begin () returns an iterator. Svec.begin () +svec.size ()/2is the intermediate data element that corresponds to the Svec vector. List<string> Slist ( -); 64 empty strings were initialized. or list<.string> Slist ( -,"Hello"); Initialize to 64 hello strings. Define a class Foo, and then use Vector<foo> a (Ten); Initialize 10 Foo objects, and vector<foo> A;,vector<foo> A (Ten); Call the default constructor, so if Foo doesn't have a default constructor, then it's a mistake. If Vector<foo> A (Ten,1); Call Foo's constructor with a parameter of 1, followed by 1 as the formal parameter list. The operation of the sequential container (1The vector list Deque operates similarly. container-defined type aliases, vector<int>:: Size_type A1 (often replaced by int A1 in for); iterator const_iterator (const container Returns const iterator) Reverse_iterator (corresponds to Rbegin,rend) Const_reverse_iterator difference_type value_type Reference const_reference type. The operation of the sequential container (2) C.push_back (), C.push_front () (vector not), C.insert (p, value), inserted in front of the element referred to by P. C.insert (p,num,value); Insert num value in front of P. C.insert (P, BEGINP, ENDP), sequential container operations (3relational operations, the container of the comparison must have the same data type sequence as the easy operation (4size () returns the number of data, max_size () returns the maximum number of data, empty (), resize (), and other sequential container operations (5) Access Element (return reference): C.back (), C.front (), c[n],c.at (n) The following two are only valid for vectors and deque, have no effect on list, and use at is better than [], especially when dealing with exceptions. The C.begin () returns an iterator, which is a pointer. Vector<int>::reference A =ivec.front (); Vector<int>::reference A = *Ivec.begin (); because Ivec.begin () returns an iterator, use a pointer. Sequence-prone operations (6Delete the element c.erase (p), c.erase (b, E), C.clear (), C.pop_back (), C.pop_front (). The Pop_front is only available for list and deque. List<string>::iterator iter = Find (B,e,"value"); E represents iterators, which are removed, not included. The operations of the S sequential container (7) Assignment and Exchange C1=The C2 c1.swap (C2) type must be the same to be done, c1.assign (b, t), type-compatible vector container of the self-growth vector with an array, but there are more advantages of the array. The vecv.capacity () returns a vector for how much data can be stored, but the capacity is self-growing, increasing each time% or and use of C + +, there is no need to control, and Vecv.size is how much data is stored in the array. Reserve  Sequential container selection vector deque (array form, so insert delete operation will be very slow, but sort, find soon) list is a linked list, so insert delete operation Insert Eraser very quickly, but sorting sort find binary_search very slow. Push_back to list soon. Methods for constructing a string objectstringS1 (S2) S1 (5,'a') s1="Str"S1 (S.begin (), S.end ()) and so on modify the method of the String object S.intert s.assignstring Object comparison s.compare (s2) and so on map Multimap is also a container, is the red and black tree structure insert data: Map<int,string> A; A.insert (map<int,string>::value_type (1," One")); A.insert (Make_pair (-1," Both"));(most commonly used), A.insert (pair<int,string> ( -,"One hundred")); a[ +]="One thousand", assigning a data to a map, passing a key-value pair, a.size (), and getting a number of key-value pairs. All containers have iterators with corresponding iterators. The corresponding key value can be obtained through an iterator:map<int,string>::const_iterator i; i = A.begin (); i->first; i->second; get the corresponding value, here is the int and string value, Multimap and map, just need to put the duplicate data, the use of Multimap, and can use count ( -) gets the number containing 100, and the fourth array form, i.e. a[ +]="One Thounsand"cannot be used in Multimap. Lookup (because map is a red-black tree structure, data search lookup will soon): Map<int,string>::const_iterator i = A.find ( -);if(I!=a.end ()),{cout<<"no found the"}; You can also map directly, or a dictionary, or an associative array. Using a[ -] and use A.find ( -), the return result will be "one hundrred". Delete: A.erase ( -)if(A.rease ( -) >0) {cout<<"Delete Success"} a.erase (b, E); B and E are the beginning iterators and the end iterators, respectively. Set and Multiset are set and multi-set. It is also a container, red-black tree structure. Set<int>A; There are operation inserts, Count Find,erase. Similarly multiset can also allow repetition, but set does not allow repetition. Note that it is not possible to modify through find because the set and multiset are automatically sorted each time the data is inserted ... Introduction to STL Algorithms, 100 + algorithms, function objects, function adapters, three header files # include<algorithm> <numeric> <functional>Introduction to Function Object For_each (start pointer, end pointer, function or function object), e.g. For_each (Ivec.begin (), Ivec.end (), display ()); Greater<int> (), less<int> (),plus<int>() and so on, are some predefined function objects. A class is used as a function object, using operator, the benefit of a function object: generally faster than the normal function, has its own state. For example: The following is a function object, which can be directly printed () when called, and the value of a, using this class, as with a functionclassprint{ Public: void operator()(intElemConst{//when called, the Operator function method is called automatically .cout<<elem<<"'; }}; Function Adapter count_if (Ivec.begin (). Ivec.end (), bind2nd (Greater<int> (),4) where bind2nd is a predefined function adapter that represents a number greater than 4. Elemental Calculation algorithm: The common count count_if can be used for all containers at a relatively slow rate, such as Count (Ivec.begin (), Ivec.end () ,4), the calculation of this ivec contains several 4, count_if (Ivec.begin (), ivec.end (), function or function object), which evaluates the number of functions or function objects in the Ivec. The element calculation algorithm for associative containers, such as Set.count, Map.count, Multiset.count, Multimap.count, is faster than a general-purpose computational container. Minimum maximum value algorithm: Min_element (b, E); Min_element (b, E, op) in the same vein as Max. Where OP is a function or function object. Lookup Algorithm (1Find find_if lookup efficiency is slower, if it is an algorithm of the ordered space, generally with the associative container adapter comes with the algorithm that. The string type cannot use Find and find_if, and the result of the lookup is an iterator. Find (b, E,4); The first 4 will be found, returning the corresponding iterator, pointing to the corresponding value. Tea Residue Algorithm (2) Search_n (b, E, C, N) The starting position of a continuous number greater than N. Search_n (b, E, C, N,greaater<int>()) The starting position of a number of consecutive C greater than N. Find Algorithm (3search () find_end (), is a pair, search () is preceded by a lookup, and find_end () is searched from behind. Search (L.begin (), L.end (), K.begin (), K.end ()), and in the beginning and end of L, find data from the beginning of K to the end, for example from L (1 2 3 4 5 6) Find K (4 5 6); Returns the corresponding starting position in L. Lookup Algorithm (4) find_first_of (b, E, SB, SE); Find_first_of (b, E, SE, BP); There is no find_last_of (typically implemented with a reverse iterator), where you can find the starting position of any number in the B,e that contains SB to SE. So it's what we found. The first data in SB to SE appears in the starting position in B to E. The string lookup function compares to the STL lookup algorithm, first of all, these methods are member functions of string, and the STL is the corresponding method in algorithm:string: Find Stl:find;string: RFind stl:find+ Reverse iterator;string: Find,stl:search;string: RFind, Stl:find_end;string: Find_first_of stl:find_first_of;stringfind_last_of,stl:find_first_of+ reverse iterator; reverse iterator vector<int>::reverse_iter Irve, Irve.Base(); the output is the corresponding forward position;string:: NPOs, corresponding string custom member variable; lookup algorithm (5) Adjacent_find (b, e); Find two consecutive equal or adjacent_find (b, E, p), two consecutive compound predicate rules two; the lookup algorithm should be used properly, for example, if it is an ordered interval, Use the ordered interval lookup algorithm such as Binary_search () and so on. Lookup Algorithm (6ordered interval lookup, the requirements must first be ordered, so that the lookup is relatively fast, Binary_search (b, E, V) dichotomy to find the number V, or with a predicate p lookup, Binary_search (b, E, V, p); Interval lookup: Includes (B,e, SB,SE) or with predicate includes (B,E,SB,SE,P), Lower_bound (), Upper_bound (), Equal_range (); Lookup Algorithm (7(ordered interval algorithm must be sorted first) Lower_bound (b,e,v), Upper_bound (b,e,v), lower find the position of the first number of V, here is index (starting from 0), Upper is the last position to find a value of V, so the two algorithms are primarily used to find the location of a data in an ordered data to facilitate insert operations. Equal_range () returns a pair of iterators that include both Lower_bound and upper_bound, such as pair<list<int>::iterator, list<int::iterator>> range; Range =Equal_range (b, E, V), through Range.first () and Range.second (); If the associated container is concerned, then do not use these methods, because the associative container has the corresponding algorithm, the performance is more; For_each () algorithm: For_ Each (B,E,P) can traverse the data, modify the data with the function object, and use the return value of For_each. If P is a function object, the return value is also a function object, such as Meanvalue MV=For_each (Ivec.begin (), Ivec.end (), Meanvalue ()), Algorithm Exchange swap_ranges (B,E,B2), if all data exchange, and is the same data type Exchange, one with the container member function swap () Fill new value: (Modified algorithm) fill (b,e,v), after filling, the original was replaced, Fill_n (b,n,v) Generate (B,e,p) Generate_n (b,n,p). V is the value and P is the function object. Replacement algorithm: replace (B,E,OV,NV); Replace the old value ov with the new value nv,replace_if (b,e,p,v) replace_copy (B1,E1,B2,OV,NV) replace_copy_if (b1,e1,b2,p,v) Delete algorithm (1): Remove (b,e,v) vemove_if (b,e,p) Here is a tombstone, not a real delete, here is the end of the deletion of the last element, because, remove the delete operation is only after the copy to the back, to overwrite, The value of the part that is not moved is not constant. That is, list:1 2 3 4 5, remove (B,e,3), it becomes 12 4 5 4 5The last two generally use the Delete member function of the container to delete, erase (end, List.end ()) is the real delete after the 45; Delete Algorithm (2): Remove_copy () remove_copy_if (), copies the data from one container to another, and removes it using the remove logic during the copy process. Delete Algorithm (3): Unique (B,e) or unique (b,e,p) unique_copy (B,E,NEWB) unique_copy (b,e,,newb,p), the algorithm of deleting successive repeated numbers or removing successive numbers that satisfy the second number of P conditions , note that there is no unique_if and unique_copy_if reversal and rotation: reverse () reverse_copy () rotate () rotate_copy () algorithm permutation combination: Before use, the data will generally need to be sorted first Next_ Permutation (b,e) The next permutation combination, if the return value is true, indicates that the permutation is not finished, there are permutations, otherwise there is no next permutation. Prev_permutation (b,e) and next reflow partitioning algorithm: Randon_shuffer (b,e) randomly reflow, like washing poker, re-upset. Partition (B,E,P) put the data in accordance with rule p in front, the others are partitioned later, and after partitioning, each area is also scrambled, the algorithm return value is an iterator, that is, the location of the partition demarcation. Stable_partition (b,e,p), a stable partition, that conforms to the rule p in front, does not conform to the rules in the back, but the relative order in each area is constant. Sort algorithm: Sort (b,e) default from small to large sort (b,e,p) stable_sort (b,e) Stable_sort (b,e,p), note: The sorting algorithm here is not suitable for random access containers, so it is not suitable for the list container, Because the list container cannot be accessed randomly. Local sort: Partial_sort (b,se,e) The sort of data between B and E, if the sorted sequence is in the position of SE, then none of the following is sorted, so how many of them are sorted without knowing. Partial_sort (b,se,e,p) partial_sort_copy (sb,se,db,de) partial_sort_copy (sb,se,db,de,p) is sorted according to the nth element: Nth_element (b, N,e) sort between B and E, and take the nth end, so know that there are n elements sorted. Nth_element (b,n,e,p) compares the partial () algorithm. Heap Sorting algorithm: Make_heap (b,e) will be sorted into piles, that is, binary tree rules. Push_heap (b,e) adds a data to the heap, provided that the push data is first push to the end of the original data, and then the binary tree is sorted to form a new heap.Pop_heap (b,e) puts the largest, or top-of-the-tree elements at the end, and the rest of the data is re-piled and sorted by a two-fork tree. Sort_heap sort the heap, forming a sort of ordinary, binary tree sort,

C + + Intermediate STL Basic Learning (II.)

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.