/ * Connect on the article:
I use these examples to demonstrate the general operation of the List. If you understand these basic principles, you can use STL without doubt, I suggest 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 General Algorithm Find () Find Objects in List How do we find in list? What about? 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.