First, STL introduction
STL (Standard Template Library, Standard Template Library) is a collective name of a series of software developed in HP Lab. It is developed by Alexander Stepanov, Meng Lee, and David R Musser working in HP laboratory. Although it is now mainly in C , the technology has existed for a long time before being introduced into C .
STL's code is divided into three categories: Algorithm (algorithm), container (container), and iTerator (iterator), almost all code uses template classes and template functions, which is compared to traditional The library of functions and classes is a better code reuse opportunity. In C standards, STL is organized to include the following 13 headers: , , , , , ,
Second, algorithm
One consensus that everyone can achieve is that the library has a crucial role in the selection of data types. For example, a function of a square root, is definitely a highly use integer as its parameter type when using floating point numbers as its parameter type. The mechanism of C through the template allows for postponed some types of options until the STL provides considerable useful algorithms for the Template or when the template is turned. It is in a valid framework to complete these algorithms - you can divide all types into a few categories, then you can use a type in the template parameter to replace other types in the same class.
STL provides a template function for approximately 100 implementation algorithms, such as the algorithm for_each to call each element in the specified sequence to call the specified function, Stable_sort, stabilize the sequence with the rules you specify, and the like. In this way, as long as we are familiar with STL, many code can be greatly limited, only need to call one or two algorithm templates and greatly enhance efficiency.
The algorithm part is mainly composed of header file , and . is the biggest one in all STL header files (although it is very well understood), it is composed of a large stack of model functions, which can be considered to be independent, which is commonly used. Functional range involves comparison, exchange, look, traversal operation, replication, modification, removal, reversing, sorting, merge, etc. The size is small, including only a few template functions that make simple mathematics operations above the sequence, including some of the operations on the sequence. defines some template classes to declare function objects.
Third, container
During the actual development process, the importance of the data structure itself will not be inferior to the importance of the algorithm of the data structure, and when there is a part of the program high, the selection of the data structure is more important.
The classic data is limited, but we often repeat some code written in order to implement the structure of the vector, linked list, which is very similar, but in order to adapt to different data changes. The STL container provides us with convenience, which allows us to repeat the data structure of the existing implementation of the implementation of their specific types, by setting some template classes, STL containers provide support for the most common data structure, these templates The parameter allows us to specify the data type of the elements in the container, you can simplify our many repetitions of work. The container portion is mainly composed of header file , , , ,
Data Structure Description Implement Head File Vector (VECTOR) Continuously Stored Elements List (List) Bidirectional Links consisting of nodes, each node contains an element Double queue (Deque) continuous storage pointing to different elements The array of pointers is composed of Collection (SET), which consists of a node, each node contains an element, and the node is arranged in a predicate, no two different elements. Ability to have the same order Multiset allows the set stack (stack) of two order phases stack (queue) first-out The order of the "priority_queue" element is a collection of a queue mapping (MAP) determined by a predicate that acts on the stored value, a collection of {keys, value}, Playing
Fourth, iterator
The iterator to say is the most basic part of the object, but it is difficult to understand that it is more laborious than the top (at least the author). Software design has a basic principle, all issues can be simplified by introducing an indirect layer, which is simplified in STL to use iterators. In summary, the iterator is used in STL to link algorithms and containers to a viscous agent. Almost all algorithms provided by STL are operated by the iterator access element sequence, each container defines the iterator that itself is used to access the elements in the container.
The iterator part is mainly composed of header file , and . is a small header file that includes a statement through several templates that runs through in STL, and many methods used in , and is very difficult for the description of It assigns storage space in different forms of elements in the container, but also for the temporary object providing mechanism generated during certain algorithms, the main part of is template ALLOCATOR, which is responsible for generating all containers Default dispenser.
5. Suggestions for beginners learn STL
For readers who haven't learned STL before, the above text is just a generally described STL's framework, which is slightly slightly slightly helping you understand the STL mechanism and even STL, which is not only because of deep STL There is a comprehensive understanding of the advanced application of C , more than three partial algorithms of STL, and the container and iterator three parts are homogeneous or closely combined. From the conceptual part of the concept, it is an iterator, but the direct learning iterator will encounter a lot of abstract boring and cumbersome details, but do not really understand the iterator is unable to go directly to the other two parts of learning (at least the source code) It is like this. It can be said that the method of adapting to the STL processing problem is to take a certain amount of time, but at the expense of this, STL has achieved a very valuable independence, which can know some data structure as little as possible through iterators. In the case of the operation of this structure, the friends who determined that STL to be drilled, don't be knocked down by the difficulties. In fact, the model of STL is relatively unified, as long as it adapts to it, there will be no big changes from a STL tool to another tool. There are also two views on STL use. The first one considered that the maximum role of STL is to act as a classic data structure and algorithm textbook because its source code involves many specific implementations. The second one believes that the original intention of STL is to simplify design, avoid duplication of labor, improve programming efficiency, so it should be "applied first", and do not have to be more important for source code. The author believes that the analysis source code and application are not contradictory. It can improve our understanding of the application by analyzing the source code, and of course, according to the specific purpose, there may be different focuses.
The last thing to say is that STL is part of the ANSI / ISO C standard, so for a process that can have a variety of C implementation, first considering the template (efficient and portable) of STL (efficient and portable), followed by each The corresponding libraries of the manufacturer (efficient but portable are not good) and write code (good portability but low efficiency).
/// 2 /// STL concept In STL, large to three main functions. Sizes, (for example, Vector, List, .....), algorithm part (such as sort, find. ..), most tools (such as auto_ptr, make_pair ....), where the Collect Class and the algorithm are most important. STL uses a data type called Iterator (Chinese people flushing generic indicators). Connect the Collect class and algorithm part. To achieve the reuse algorithm and Collect Class. These things further abstain in STL. Therefore, STL orders a bunch of abstract behavior called Concept. You can imagine Concept is Explain some behavior. As long as a certain type does not look at the behavior described in Concept. This type has this concept. For example, if there is a Concept C1, C2. Algorithm A1, A2. Data type D1 has C1 behavior, D2 has C1 , C2. If A1 requires a type of C1, it is necessary to use the C1 data type. There are D1 and D2 in this example. Such as the A2 requires the type of C1. Only D2 can use .STL uses abstract behavior definitions and implements them to reuse the reuse of algorithms and data types. Iterator is a very important concept in STL, Iterator and C Point, but he is not Indicators (Note Iterator is Point in some cases). He offers a function similar to Point, such as ' ' operation indicates to the next ELEMENT, '*' operation indicates access Iterator. Pointing Element (using 'pointing' here "is not very good). You can visit the content stored in Collectes using Iterator. For example, an example shows the functionality of ITeraotr. Vector is one of the many Collect Class in STL. Vector provided Member Function of Begin () and End () to get the first element of Element, and the next Element's next element. You can use: std :: vector vtint; vtint. Push_back (1); ..... / hypothesis Tint has made a lot of different movements, such as push_back ... std :: vector :: iterator itbegin = vtint.begin (); std :: vector :: item ity = vtint.end (); For (; itbegin! = ity; iTBegin) // Visit ITBEGIN to ITEND does not contain all Element {int x = * itbegin; // Get ITBEGIN Points * ITBEGIN = ....; // Store information to ITBEGIN Points} This example has a similar function with C Point. Both all STL algorithms are required to input data, such as the Sort algorithm, require two Iterator, then put these two The data between Iterator is sorted. When introduced to Iterator, sort can be sorted, and the example I. Use the standard output in STL. SAY HELLO # include // STL input and output contains files. There is no use in STL. H or .hpp, etc. Int main (int Argc, char * argv []) {std :: cout << "Hello !! this is stl" << std :: endl;
// Use STL's standard output, STD is STL's Namespace, so use std :: cout return 0;} ii. From standard input reading strings, sorted, then output #include // STL input and output The algorithm containing the file #include // STL contains a string #include // STL of the string #include // STL's CLECT CLASS This is a class constinary display of the array = 5; INT main (int Argc, char * argv []) {std :: vector vtstring; // Declare a string vectorStd :: string straTemp; // Declare a string for (int i = 0; I > strTemtring.push_back (strtemp); // will read the word The last side of VTSTString} std :: sort (VTSTRING.BEGIN (), vtstring.end ()); // Sultystd :: Copy (VTSTSTSTSTRING.BEGIN (), VTSTSTSTRING.EGIN () Std :: String> (std :: string> (std :: cout, "/ n"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) Algorithm .///3///// Program: Vector Demo One // Purpose: Understand the vector // #include "stdafx.h" in STL - If you use the precompiled header file, you contain this header file # Include // STL vector header file. There is no ".h" here. #include // contains the header file of the COUT object. Using namespace std; // guarantees that members in the STD namespace can be used in the program. Char * szhw = "Hello World"; // This is an array of characters and ends with "/ 0". INT main (int Argc, char * argv []) {Vector vec; // Declare a character vector VECTOR (Array in STL) / / Define a cursor Iterator for a character array. Vector :: item vector vi; // initialize the character, loop the entire string, // is used to fill the data into the character vector until the end of "/ 0". Char * cptr = szhw; // points a pointer to "Hello World" string while (* cptr! = '/ 0') {vec.push_back (* cptr); CPTR ;} // push_back function put data in vector The tail. // Display the characters in the vector in the console for (vi = vec.begin (); vi! = Vec.end (); vi ) // This is the standardized start of the STL loop - usually " ! = ", Not" <"// because" <"is not defined in some containers.
// begin () Returns the cursor of the vector starting element (Ite () returns the cursor (Iterator) of the vectors of the vector. {cout << * vi;} // Use operator "*" to extract data from the cursor pointer. COUT << Endl; // Remove Return 0;} / 4 / Using STL Universal Algorithm Find () Find objects in list How do we find things in LIST? STL's general algorithm Find () and FIND_IF () can do this. Like for_each (), count (), count_if (), these algorithms also use the Iterator range, which indicates a list or any other container to process. Usually the first Iterator refers to the position of the beginning, and the Iterator pointed to stop processing. The elements pointed out by times Iterator are not processed. This is find () how to work: / * || How to find things in an set list * / #include #include #include # int main (void) {list fruit; List :: Iterator Fruititerator; # fruit.push_back ("apple"); Fruit.push_Back ("PineApple"); Fruit.push_Back ("star apple"); # fruititerator = find (fruit.begin (), Fruit .end (), "pineapple"); # if (fruititerator == fruit.end ()) {cout << "fruit not found in list" << Endl;} else {cout << * fruititerator << endl;} } The output is: PineApple If the object does not find, it will return Fruit.end () value. If you find it, return a point to Iterator to find the object -------------- -------------------------------------------------- ---------------- Use the STL General Algorithm Find_if () Search Object in List This is a more powerful version of Find (). This example demonstrates find_if (), which receives the parameters of a function object as a parameter and uses it to do more complex evaluation objects and give the lookup criteria. Suppose there are some records containing events and dates in our List. We want to find an event that happened in 1997.
/ * || How to find things in an stl list mkii * / #include #include #include # Class Eventisin1997 {public: BOOL Operator () (String & EventRecord) {// Year Field IS at position 12 for 4 characters in EventRecord return EventRecord.substr (12,4) == "1997";}}; # int main (void) {list Events; # // string positions 0123456789012345678901234567890123456789012345 Events.push_back ( " 07 January 1995 Draft plan of house prepared "); Events.push_back (" 07 February 1996 Detailed plan of house prepared "); Events.push_back (" 10 January 1997 Client agrees to job "); Events.push_back (" 15 January 1997 Builder Starts Work On Bedroom "); Events.push_back (" 30 April 1997 Builder Finishes Work "); # list :: item Eventiterator = Find_if (Events.Begin (), Events.end (), Eventisin1997 ()) ; # // Find_if Completes the first time eventisin1997 () returns true // for any Object. It Returns an iterator to this objec T Which we // can dereference to get the object, or if Eventisin1997 () never // Returned true, find_if returns end () f () {cout << "Event not found in List "<< Endl;} else {cout << * Eventiterator << Endl;}} This is the output of the program: 10 January 1997 Client Agrees to job ----------------- -------------------------------------------------- ------------- Using the STL General Algorithm Search to find a sequence in the list, some characters are well processed in the STL container, let us take a look at a difficult character sequence. We will define a list to place characters. List characters; Now we have a character sequence, it does not use any help, you will know and manage the memory. It knows where it starts, where is it ended. It is very useful.
I don't know if I said the character array ended with NULL. Let's join some of the characters we like to this list: characters.push_back ('/ 0'); characters.push_back ('/ 0'); characters.push_back ('1'); characters.push_back ('2') How many empty characters we will get? INT Numberofnullcharacters (0); count (character (trans (characters.egin (), characters.end (), '/ 0', numberofnullcharacters; cout << "we have" << Numberofnullcharacters << Endl; let us find characters '1' list :: item; do = find (character = find (), character = Find (), '1'); cout << "We found" << * iter << Endl; this example demonstrates STL container Allows you to process empty characters in a more standard approach. Now let's use STL's Search algorithm to search for two NULLs in the container. Just like you guess, STL general algorithm search () is used to search for a container, but search for an element string, not like Find () and FIND_IF () Search only for individual elements. / * || How to use the Search Algorithm in an stl list * / #include #include #include # int main (void
{# List TargetCharacters; list ListOfCharacters; # TargetCharacters.push_back ( '/ 0'); TargetCharacters.push_back ( '/ 0'); # ListOfCharacters.push_back ( '1'); ListOfCharacters.push_back ( ' 2 '); ListOfCharacters.push_back (' / 0 '); ListOfCharacters.push_back (' / 0 '); # list :: iterator PositionOfNulls = search (ListOfCharacters.begin (), ListOfCharacters.end (), TargetCharacters. Begin (), targetcharacters.end ()); # ix (positionofnulls! = listofcharacters.end ()) cout << "We found the nulls << end1;} the output of the program will be this is the output of the program: We found The Nulls Search Algorithm The first appearance of the first appearance of another sequence in a sequence. In this example we found a first appearance of TargetCharacters in ListOfcharacters, TargetCharacters is a sequence containing two NULL characters. The parameters of Search are two Iterators that point to find the target and two Iterators that point to the search range. So we look for the entire sequence of TargetCharacters in the range of the entire ListOfchacTers. If TargetCharacters are found, Search returns an item of iTerator that pointing to the sequence in ListOfcharacters. If a match is not found, Search returns the value of ListOfcharacters.end (). -------------------------------------------------- ------------------------------ Use the List member function sort () sorted a list. To sort a list, we want to function sort () instead of the general algorithm sort (). All we have used algorithms are general algorithms. However, sometimes the container supports its own implementation of a special algorithm in STL, which is usually in order to improve performance. In this example, the List container has its own Sort algorithm because the general algorithm can only sort the container that provides random access elements, and because the List is implemented as a connected list, it does not support it The element is randomly accessed. So you need a special sort () member function to sort the list. For various reasons, the container supports external functions in applications that require high or special effects demand, which can be made by using the structural characteristics of the constructor.
/ * || How to sort an set list * / #include #include #include # printit (string & stringtoprint) {cout << StringToprint << Endl;} # int main (void) { List staff; list :: item; "john"); staff.push_back ("Bill"); staff.push_back ("tony"); staff.push_back ("fidel" ); Staff.push_back ("nelson"); # cout << "The unsorted list" << endl; for_each (staff.begin (), staff.end (), printit
# Staff.sort (); # cout << "The sorted list" << endl; for_each (staff.egin (), staff.end (), printit);} Output is: The unsorted List John Bill Tony Fidel Nelson The Sorted List Bill Fidel John Nelson Tony -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------- Insert the elements to list in List Member functions push_front () and push_back () add the element to the front and behind of the List. You can use INSERT () to insert the object anywhere in the list. INSERT () can join an object, a copy of an object, or an object within a range. Here is some examples in inserted objects to List: / * || Using Insert to INSERT Elements INTO A List. * / #Include # int main (void) {list list1; # / * || PUT Integers 0 to 9 in the list * / for (int i = 0; i <10; i) list1.push_back (i); # / * || insert -1 useing the insert member function || Our List Will Contain -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 * / List1.insert (List1.begin (), -1); # / * || insert an element at the end using Insert || Our List Will Contain -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 * / List1.insert (List1.END (), 10); # / * | INSERTING A RANGE From Another Container || Our List Will Contain -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 * / Int IntArray [2] = { 11, 12}; List1.insert (), & INTARRAY [0], & INTARRAY [2]); # / * || as an adrise put the code in here to print the list! || hint: use printit And Accept An Interger * /} Note that the insert () function inserts one or several elements into the location of the Iterator you point out. Your elements will appear before the location pointed out in Iterator.
-------------------------------------------------- ----------------------------- List constructor we have already defined List: list fred; you can also Like the elements that define this, and initialize its elements: // define a list of 10 elements and initialise am all to 0 list fred (10, 0); // list now Contains 0, 0, 0, 0 0, 0, 0, 0, 0, or you can define a list and initialize it with another STL container, this STL container is not necessarily a list, only the container that is the same as the element type. . Vector Harry; Harry.push_back (1); Harry.push_Back (2); # // define a list and initialise it with the elements in harry list bill (Harry.Begin (), Harry.end ( )); // Bill Now Contains 1, 2 ------------------------------------- ----------------------------------------- Use the List member function to remove the element from the list List member function pop_front () Deletes the first element in the list, and Pop_BACK () deletes the last element. The function ERASE () deletes the elements pointed out by an item. There is another erase () function to delete a range of elements. / * || Erasing Objects from a list * / #include # int main (void) {list list1; // define a list of integers # / * || Put Some Numbers in the list || IT Now Contains 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 * / for (int i = 0; i <10; i) list1.push_back (i); # list1.pop_front ); // Erase the first element 0 # list1.pop_back (); // Erase The last element 9 # list1.begin ()); // Erase The first element (1) using an itrator # list1. ERASE (List1.begin (), list1.end ()); // Erase All the remaining elements # cout << "list contacts" << list1.size () << "Elements" << Endl;} output is: List contains 0 Elements -------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Use the List member function remove () to remove the element from the list. The members of the List is used to delete elements from the list.
/ * || Using the list member function remove to remove elements * / #include #include #include # PrintIt (const string & StringToPrint) {cout << StringToPrint << endl;} # int main (void) {list birds; # birds.push_back ("cockatoo"); birds.push_back ("galah"); birds.push_back ("cockatoo"); birds.push_back ("rosella"); birds.push_back ("Corella"); # cout << "Original List with cockatoos" << Endl; for_each (birds.begin (), birds.end (), printit); # birds.remove ("cockatoo"); # cout < <"Now no cockatoos" << endl; for_each (birds.begin (), birds.end (), printit);} Output is: Original List with cockatoos cockatoo Galah Cockatoo Rosella Corella Now No cockatoos Galah Rosella Corella ------- -------------------------------------------------- -------------------------- Use STL General Algorithm Remove () Remove Element Universal Algorithm from LIST Remove () Use and List's member function Work work. In general, do not change the size of the container.
/ * || Using the generic remove algorithm to remove list elements * / #include #include #include #printit (string & assenging) {cout << astring << endl;} # int main Void) {list birds; list :: item new; "cockatoo"); birds.push_back ("galah"); birds.push_back ("cockatoo"); birds.push_back "rosella"); birds.push_back ("king parrot"); # cout << "Original List" << endl; for_each (birds.begin (), birds.end (), printit); # newnd = remove (Birds .begin (), birds.end (), "cockatoo"); # cout << endl << "List accounting to new paste the end itrator" << Endl; for_each (birds.begin (), newnd, printit); # Cout << Endl << "Original List Now. Care Required! << Endl; for_each (birds.begin (), birds.end (), printit);} The output will be Original List Cockatoo Galah Cockatoo Rostoo Galah Cockatoo Rosella King Parrot List accounting to new paste the end iprot Original List Now. Care Required! Galah Rosella King PARROT ROSELLA KING PARROT Universal Remove () Algorithm Returns a Iterator that pointing to the end of the new List. From the beginning to this new end (excluding new end elements), all elements are left after removing. You can use the List member function ERASE function to delete the part of the new end to the old end. -------------------------------------------------- ------------------------------ Use STL General Algorithm Stable_Partition () and List member function splice () to divide a list we will Complete a slightly a bit complicated example. It demonstrates the changes of the STL general algorithm stable_paartition () algorithm and a List member function splice (). Note that the use of function objects and does not use loops. Call the STL algorithm by a simple statement to control. Stable_paTition () is an interesting function. It rears elements such that the elements that meet the specified conditions are ranked in front of the elements that do not satisfy the conditions. It maintains the order relationship of two groups of elements. Splice combines elements in another list into a list. It removes elements from source list.
In this example, we want to receive some logos and four file names from the command line. The file name must "appear in order. By using Stable_Partition () we can receive and file names to any location, and put them together without chaos. Due to the ratio and lookup algorithms are easy to use, we call these algorithms to decide which flag is set and which flag is not set. I found that the container is used to manage a small amount of dynamic data. / * || Using the STL stable_partition algorithm || Takes any number of flags on the command line and || four filenames in order. * / #Include #include #include # PrintIt (string & AString
{Cout << astring << Endl;} # class isaflag {public: BOOL Operator () (string & possibleflag) {Return Possibleflag.substr (0,1) == "-";}}; operator () (string & StringToCheck) {return IsAFlag () (StringToCheck);!}}; # class IsHelpFlag {public: bool operator () (string & PossibleHelpFlag) {return PossibleHelpFlag == "- h";}}; # int main (int Argc, char * argv []) {list cmdlineParameters; // the command line parameters list :: items list Flags; // list of flags list filenames; // list of filenames # for (int i = 0; i
# // Splice any flags from the original CmdLineParameters list into Flags list Flags.splice (Flags.begin (), CmdLineParameters, CmdLineParameters.begin (), StartOfFiles);. (! Flags.empty ()) # if {cout << "Flags Specified WERE:" << endl; for_each (flags.begin (), flags.end (), printit;} else {cout << "no flags were specified" << endl;} # // parameters list Now contains only filenames Splice them into fileNames list FileNames.splice (FileNames.begin (), CmdLineParameters, CmdLineParameters.begin (), CmdLineParameters.end ());.. (! FileNames.empty ()) # if {cout << " Files Specified (in Order) WERE: "<< endl; for_each (filenames.begin (), filenames.end (), printit;} else {cout <<" no files were specified "<< Endl;} # // Check if the help flag Was specifiediff (Flags.begin (), Flags.eL (), ishelpflag ())! = flags.end ()) {cout << "The help flag was specified" << endl; } # // open the files and do wherever you do #} gives this command line: TEST17 -W Linux -o is -w great Yes: The Wrong Number (3) of File Names Were Specified Command Line Parameters After Stable Partition -w -w Linux Is Great Flags Specified Were: -w -w Files Specified (in Order) WERE: Linux IS Great -------------------------------------------------- ------------------------------ Conclusion We just talk about things that you can do with LIST. We did not explain the user-defined class of an object, although this is not difficult. If you understand the concept behind these algorithms just said, then the rest of the algorithms should have no problem. The most important thing to use STL is the basic theory. The key to STL is actually Iterator. The STL algorithm uses Iterator as a parameter, which points out a range, sometimes a range, sometimes two.