STL introduction, standard template library

zhaozj2021-02-16  57

About STL, the Standard Template Library Author: Scott Field This article is a new extension on the C language - Standard Template Library (Standard Template Library), also known as STL. When I first intended to write an article about STL, I had to admit that I went to underestimate the depth and breadth of this topic. There are a lot of content to be covered, and there are a lot of books that describe STL. So I re-consider my original idea. Why do I have to write this article, why do you want to contribute? What will this use? Is there any need to come back about STL? When I opened the Musser and Saini page, I saw the programming era ablation in front of me. I can see that the night has disappeared, and the target software project has appeared. I saw the maintenance code. One year has passed, I use STL written software still easy to maintain. It is a very surprised that others can have a good maintenance! However, I also remember that it is difficult to understand those technical terms when they start. Once, I bought Musser & Saini, and everything appeared in turn, but there were some good examples who were most eager to get there. When I started, Stroustrup as part of C has not come yet, it covers STL. So I would like to write an article about a real life of a STL programmer. If I have some good examples in my hand, especially the new topic like this, I will learn faster. Another thing is that STL should be very easy to use. Therefore, in theory, we should start using STL immediately. What is STL? STL is Standard Template Library, standard template library. This may be the most boring term for the most exciting tool in history. Fundamentally, STL is a collection of "containers", these "containers" include List, Vector, SET, MAP, etc., STL is also a collection of algorithms and other components. The collection of "containers" and algorithms here refers to a masterpiece of many smart people in the world. The purpose of STL is to standardize components so you don't have to revoke them. You can only use these ready-made components. STL is now part of C , so there is no additional installation. It is built within your compiler. Because STL's list is a simple container, I intend to introduce STL how to use it from it. If you know this concept, there is no problem in other things. In addition, the List container is quite simple, we will see this. In this article we will see how to define and initialize a list, calculate the number of elements, find elements, delete elements, and some other operations from a list. To do this, we will discuss two different algorithms, and the STL general algorithm can operate more than one container, and the member function of the List is a proprietary operation of the LIST container. This is a simplicity of three primary STL components. The STL container can save objects, built-in objects, and class objects. They safely save objects and define the interface we can operate. Eggs put on the egg rack will not roll to the table. They are safe. Therefore, the objects in the STL container are also very secure. I know this metaphor is very old soil, but it is correct. The STL algorithm is a standard algorithm that we can apply them on those containers. These algorithms have very famous execution characteristics. They can sort objects, delete them, give them a record, compare, find special objects, merge them into another container, and perform other useful operations. STL Iterator is like a pointer to the object in the container.

The algorithm of STL uses Iterator on the container on the container. Iterator sets the boundary of the algorithm, the length of the container, and some things. For example, some Iterator only allows algorithm reading elements, some let algorithm write elements, and there are some of them. Iterator also determines the direction processed in the container. You can get a Iterator that pointing to a container start position by calling a member function becom () of the container. You can call a container's END () function to get the last value of the past (that is, the value of the value stops). This is the other thing of STL, the container, algorithm, and the Iterator that allows algorithms to work on the elements in the container. The algorithm operates objects in a suitable, standard approach, and can get the exact length of the container via Iterator. Once these do this, they will not "run out the boundary." There are also other components that have functional enhanced functions of these core components, such as function objects. We will see examples about these, now let's take a look at the List of STL. Define a list we can define a STL's list: #include #include int main (void) {list Milkshakes;} This is, you have defined a list. Is it simple? List Milkshakes This sentence is that you declare an instance of the list template class, and then an object of instantiation this class. But don't worry about this. In this step in this, you only need to know that you define a string LIST. You need to include the header file that provides the STL List class. I use GCC 2.7.2 to compile this test program on my Linux, for example: g test1.cpp -otest1 Note that iostream.h This header file has been abandoned by the STL's header file. This is why there is no reason in this example. Now we have a list, we can use it to use it. We will add a string to this list. There is a very important thing called List value type. The value type is the type of object in the List. In this example, this List's value type is a string, string because this list is used to make strings.

I use the list and the member function push_back push_front element is inserted into a list in #include #include # int main (void) {list Milkshakes; Milkshakes.push_back ( "Chocolate"); Milkshakes.push_back ( "Strawberry"); Milkshakes.push_front ( "Lime"); Milkshakes.push_front ( "Vanilla");.} We now have a list with four strings in it The list member function push_back () places an object onto the back of the list. The list member function push_front () puts one on the front. I often push_back () some error messages onto a list, and then push_front () a title on the list so it prints before the error messages. we now have a 4 strings are in list. The member function of the List puts an object behind a list, while push_front () puts the object in front. I usually put some error information push_back () into a list, then push_front () a title to list so that it will print it before this error message.

The member function EMPTY () of the list member function Empty () List knows if a list is very important. If the list is empty, the member function of Empty () is true. I usually use it like this. I use push_back () to put the error message in the list. Then, by calling EMPTY (), I can say that this program reports an error. If I define a list to put information, a warning, a serious error, I can easily say that the type of error occurs easily by using Empty (). I can organize these LISTs and then use the title to organize them before printing them, or sort them into classes. This is my meaning: / * || Using a list to track and report program messages and status * / #include #include #include # int main (void) {#define OK 0 #define INFO 1 #define WARNING 2 # int return_code; # list InfoMessages; list <: string> WarningMessages; # // during a program these messages are loaded at various points InfoMessages.push_back ( "Info: Program started" ); // Do Work ... WarningMessages.push_back ("Warning: No Customer Records Have Been Found"); // Do Work ... # Return_code = OK; # if (! InfMessages.empty ()) {//// There were info messagein infMessages.push_front ("INFORMATIONAL MESSAGES:"); // ... print the info messages list, we'll see how late return_code = info;} # i (! WarningMESSAGES.EMPTY ()) {// There WERE WARNING Messages WarningMessages.push_front ("Warning Messages:"); // ... print the warning message list, we'll see how laturn_code = warning; } # // if there. I (infMessages.empty () && warningMesses.empty ()) {cout << "there"} # Return Return_code;}

Use the for loop to handle elements in the list. We want to traverse a list, such as printing all objects to see the results of different operations on the list. To traverse a list of an element, we can do this: / * || How to print the contents of a simple st.whew! * / #Include #include #include # int main (void) {list Milkshakes; list :: iterator MilkshakeIterator; # Milkshakes.push_back ( "Chocolate"); Milkshakes.push_back ( "Strawberry"); Milkshakes.push_front ( "Lime") ; Milkshakes.push_front ( "Vanilla"); # // print the milkshakes Milkshakes.push_front ( "The Milkshake Menu"); Milkshakes.push_back ( "*** Thats the end ***"); for (MilkshakeIterator = Milkshakes. Begin (); Milkshakeiterator! = Milkshakes.eerator) {// dereference The itrator to get the element cout << * Milkshakeiterator << Endl;}} This program defines an Iterator, Milkshakeiterator. We point it to the first element of this List. This can call MilkShakes.Begin () to do it, it will return a Iterator pointing to the List. Then we compare it and the return value of Milkshakes.end (). When we arrived there, stopped. The end () function of the container returns an item of Iterator to the last position of the container. When we arrive there, stop the operation. We cannot ignore the return value of the END () function of the container. We only know that it means that the end of this container has been processed, should stop processing. All STL containers must do this. In the above example, each time the FOR cycle is executed, we repeatedly refer to Iterator to get our printed string. In STL programming, we use one or more items in each algorithm. We use them to access objects in the container. To access a given object, let's point to it, then indirectly quote this item. This List container is like what you think, it does not support a number of objects to point to one number in Iterator. That is, we can't use Milkshakes.Begin () 2 to point to the third object in the list, because the STL's list is implemented with a double-stranded list, which does not support random access. Vector and Deque (vector and dual queues) and some other STL containers can support random access. The above program prints out the contents in the list. Anyone read it, you can figure out how it works. It uses standard Iterator and standard LIST containers. There is not much programmer relying on what it put in it, just standard C .

This is an important step. This example uses STL to make our software more standard. Using STL's general algorithm for_each to handle elements in LIST using STL LIST and ITERATOR, we want to initialize, compare, and give Iterator increments to traverse this container. STL - common for_each algorithms can alleviate our work. / * || How to print a Simple Stl list mkii * / #include #include #include #include #printiT (string & stringtoprint) {cout << StringToprint << Endl ;} # int main (void) {list FruitAndVegetables; FruitAndVegetables.push_back ( "carrot"); FruitAndVegetables.push_back ( "pumpkin"); FruitAndVegetables.push_back ( "potato"); FruitAndVegetables.push_front ( "apple") FruitandVegetables.push_front ("pinepple"); # for_each (fruitandvegetables.begin (), fruitandvegetables.end (), printit);} In this program we use STL's general algorithm for_each () to traverse a range of Iterator, then Call printit () to handle each object. We don't need to initialize, compare and give Iterator increments. FOR_EACH () has completed these work for us. We execute the operation on the object being packed in this function, we don't have to do that loop, our code is clearer. The FOR_EACH algorithm references the concept of the Iterator range, which is the range pointed out by the starting iterator and one end Iterator. The starting item indicates where the operation is started, the end Iterator indicates where the end, but it is not included in this range.

Statify the number of elements in the List using STL's general algorithm count (). The general algorithm of STL count () and count_it () are used to record objects in the container. Just like for_each (), count () and count_if () algorithms are also done in the iTerator range. Let us have a number of people in the LIST of a student test. This is a integer list. / * || How to count Objects in an stlist * / #include #include # int main (void) {list score; # scores.push_back (100); score.push_back (80 ); Score.push_back (45); score.push_back (75); score.push_back (99); scores.push_back (100); # int numberof100scores (0); count (scores.begin (), scorend () , 100, Numberof100Scores); # cout << "there" << Numberof100scores << "scorers of 100" << Endl;} The count () Algorithm Counts The number of objects equal to a ceertain value. In the Above Example IT CHECKS EACH INTEGER OBJECT IN A List Against 100. IT Increments The Variable Numberof100scores Each Time A Container Object Equals 100. The Output of The Program Is Count () Algorithm Statistics Obtained by an object of a certain value. The above example exams each of the integer objects in the List. Objects in each container is equal to 100, it gives Numberof100Scores plus 1. This is the output of the program: There Were 2 Scorers of 100

Using STL's general algorithm count_if () to count the number of elements in List count_if () is a more interesting version of count (). He used STL's new component, function object. Count_if () Belts a parameter of a function object. Function object is a class with at least one Operator () method. Some STL algorithms are used as a parameter to receive function objects and call the Operator () method of this function object. The function object returns TRUE or FALSE when the STL algorithm calls Operator. They determine this function based on this. It is more clear to give an example. Count_if () makes a more complex assessment than Count () by passing a function object to determine if an object should be recorded. In this example we will sell the number of toothbrush. We will submit sales records containing four characters and product descriptions. / * || Using a function Object to help count things * / #include #include #include # const string toothbrushcode ("0003"); # class isatoothbrush {public: BOOL Operator () () string & SalesRecord) {return SalesRecord.substr (0,4) == ToothbrushCode;}}; # int main (void) {list SalesRecords; # SalesRecords.push_back ( "0001 Soap"); SalesRecords.push_back ( "0002 Shampoo "); SalesRecords.push_back (" 0003 Toothbrush "); SalesRecords.push_back (" 0004 Toothpaste "); SalesRecords.push_back (" 0003 Toothbrush "); # int NumberOfToothbrushes (0); count_if (SalesRecords.begin (), SalesRecords .end (), isatoothbrushes; # cout << "there" << Numberoftoothbrushes << "TOTHBRUSHES SOLD" << Endl;} This is the output of this program: there is a total of Selling Two toothbrush) This program works this way: Define a function object class isatoothbrush, which can determine if the sale is a toothbrush. If this record is a record of selling a toothbrush, the function calls Operator () returns a true, otherwise returns false. The count_if () algorithm handles the container object by the range of first and second two Iterator parameters. It will increase the value of NumberoftOothbrushes to the objects in the container that returns True in TRUE. The final result is that NumberoftOothbrushes saves the number of records of the product code domain "0003", which is the number of toothbrush. Note that the third parameter ISATOTHBRUSH () of count_if () is an object that is temporarily constructed by its constructor.

You can pass a temporary object of the ISATOTHBRUSH class to a count_if () function. Count_if () will call each object of the container to call this function. A more complex function object using count_if (). We can further study the function object. Suppose we need to pass more information to a function object. We can't do this by calling Operator because it must be defined as the type of object in a list. However, we can use any of the information we need to initialize it with any information we need for isatoothbrush. For example, we may need to have an uncertain code for each toothbrush. We can add this information to the following function object: / * || Using a more complex function object * / #include #include #include #include # Class isatoothbrush {public: IsAToothbrush (string & InToothbrushCode): ToothbrushCode (InToothbrushCode) {} bool operator () (string & SalesRecord) {return SalesRecord.substr (0,4) == ToothbrushCode;} private: string ToothbrushCode;}; # int main (void ) {list SalesRecords; # SalesRecords.push_back ( "0001 Soap"); SalesRecords.push_back ( "0002 Shampoo"); SalesRecords.push_back ( "0003 Toothbrush"); SalesRecords.push_back ( "0004 Toothpaste"); SalesRecords .push_back ( "0003 Toothbrush"); # string VariableToothbrushCode ( "0003"); # int NumberOfToothbrushes (0); count_if (SalesRecords.begin (), SalesRecords.end (), IsAToothbrush (VariableToothbrushCode), NumberOfToothbrushes); cout << "There" << Numberoftoothbrushes << "TOTHBRUSHES MATCHING C ODE "<< variabletoothbrushcode <<" SOLD "<< Endl;} The output of the program is: There WERE 2 TOTHBRUSHES MATCHCHING CODE 0003 SOLD This example demonstrates how to pass information to the function object. You can define any constructor you want, you can do anything you want to do again, you can legally compile. You can see that the function object really expands the basic count algorithm. So far, we have learned:

Define a list to the list to learn how List is empty how to use for loops to traverse how List uses STL's general algorithm for_each to traverse List List member functions Begin () and end () and their meaning Iterator range concept And a range of last position is actually not handled how this is how to use the STL general algorithm count () and count_if () how to count the object in a list, how to define a function object I use these examples to demonstrate List General operation. If you understand these basic principles, you can use STL without doubt that you do some exercises. We now use some more complex operations to expand our knowledge, including List member functions and STL general algorithms. 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 that pointing to the object found.

Searching for objects in List This is a more powerful version of Find () using the STL general algorithm. 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 That Obj Ect 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 list, some characters are well processed in the STL container, let us see 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 the search "{#list> # Int main (void) {# list targetcharacters; list listofcharacters; 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 :: item (listocuracters.egin () (), targetchacters.egin () (), targetchacters.eGin (), targetchacters.egin (), targetcharacters.egin (); (Positionofnulls! = Listofcharacters.end ()) cout << "We found the nulls << endl;} the output of the program will be this is the output of the program: We found the nulls search algorithm in a sequence to find another The first appearance of the 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 ().

Sort a list using a member function sort () of the 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" << end1; for_each (staff.egin (), staff.end (), printit); # staff.sort (); # cout << "The sorted list" << Endl; for_each (staff.beach (), staff.end (), printit;} Output is: The unsorted List John Bill Tony Fidel Nelson The Sorted List Bill Fidel John Nelson Tony

Insert the member function of the List of the List to add the elements to the front and back of the LIST in the member function plug-in element. 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 defined List: list fred; you can also define a list like this, and initialize its elements: // define a list of 10 elements and initialise 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 use another STL container to initialize it, This STL container is not necessarily a list, which only needs to be the same as the same type of container. 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 List member function pop_front () delete the first element in the list, 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);} Out: Original List with cockatooos cockatoo galah cockatoo Rosella Corella Now No cockatoos Galah Rosella Corella

Use STL General Algorithm Remove () to remove element universal algorithm remote () using and List's member function works in different ways from LIST. 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 the 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) == "-";}}; # Class isafilename {public: bool 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

"Command line parameters after stable partition" << endl; for_each (CmdLineParameters.begin (), CmdLineParameters.end (), PrintIt);. # // Splice any flags from the original CmdLineParameters list into Flags list Flags.splice (Flags. Begin (), cmdlineParameters, cmdlineParameters.begin (), startoffiles); # ix (! Flags.empty ()) {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 ()); # ix (! Filenames.empty ()) {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 (Flags.Begin (), Flags.end (Flags.begin (), Flags.end ), IShelpflag ())! = Flags.end ()) {cout << "the Help flag WAS specified "<< Endl;} # // open the files and do whatver you do #} gives this command line: TEST17 -W Linux -o is -w great output is: The Wrong Number (3) of File Names Were Specified Command Line Parameters After Stable Partition -w -w Linux Is Great Flags Specified WERE: -W -O -W Files Specified (in Order) WERE: Linux is Great

Conclusion We just talk about what 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. The STL container supports Iterator, which is why we say list :: item, or list :: item, or list :: item. Iterator has a good inheritance. They are very useful. Some Itelator only supports read only a container, some only support, and some can only refer to, some are two-way. There are some iTerator support random access to a container. The STL algorithm requires an item as "power" if a container does not provide Iterator as "power", then this algorithm will not be able to compile. For example, the List container provides only two-way Iterator. The usual Sort () algorithm requires a random access to Iterator. That's why we need a special List member function sort (). To actually use STL, you need to carefully learn a variety of different items. You need to know that each container supports that type of Iterator. You still need to know that the algorithm requires that Iterator, you certainly need to know that you can have that Iterator. Using STL last year in Field, I have written several business programs with STL. It reducs my workload in many ways and also excludes a lot of logic errors. The largest procedure has about 5,000 rows. Maybe the most amazing thing is its speed. It reads and handles a 1-2 trillion report file for approximately 20 seconds. I was developed with GCC2.7.2 on Linux, and now run on the HP-UX machine. It uses a total of approximately 50 and function objects and many containers, which are available from small LIST to a 14,000 elements of MAP. The function object in a program is in a inherited tree, and the top layer function object calls the low-layer function object. I use the STL algorithm for_each (), find (), find_if (), count (), and count_if (), I try to minimize the functions inside the program, and use STL's algorithm call. STL tends to automatically control the code into clear control and support modules. By carefully using the function object and gives them meaningful names, I have made them flow in the control flow of my software. There are still many things about STL programming, I hope that you can work more enjoyable through these examples. The two books in the reference have errata on the web, you can correct them yourself. Stroustrup has a suggestion column behind each chapter, especially for scholars. The book is more tongue than the early version. It is also bigger. You can also find other textbooks about STL in the bookstore. Go and see, maybe you can find anything. Bibliography The STL TUTORIAL AND REFERENCE, DAVID MUSSER AND ATUL SAINI. Addison Wesley 1996. "STL Tutorial and Reference Manual" The C Programming Language 3e, Bjarne Stroustrup. Addison Wesley 1997.

转载请注明原文地址:https://www.9cbs.com/read-21615.html

New Post(0)