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 "in an stlist * / #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 ( ), "Pinepple"); if (Fruititerator == fruit.end ()) {cout << "fruit not found in list" << Endl;} else {cout << * fruititerator << Endl;}} output is: PineApple If you do not find the object pointed out, you will return Fruit.end () value, if you find it, return a point to the Iterator to find the object ------------------------------------------------------------------------------------ -------------------------------------------------- ------------ Use the STL general algorithm FIND_IF () Search Objects 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 set #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 object wh Ich 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: 10 January 1997 Client Agrees to job ------------------ -------------------------------------------------- ------------ Use 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 characters. 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 * / #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 :: item (ListOfchacters.egin () (), targetchacters.egin (); if (positionofneacters.egin (); if (PositionOfnulls! = ListOfchacTers.eGin (); if 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 sequence for the first appearance s position. 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 < String> Staff; List :: iterator people; staff.push_back ("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.begin (), staff.end (), printit;} Output is: The unsorted List John Bill Tony Fidel Nelson The Sorted Bill Fidel John Nelson Tony --------- -------------------------------------------------- -------------------- Member function in the List inserts the member function of the List to list "Push_Front () and push_back () add the element to the List And behind. 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 (List1.end (), & INTARRAY [0], & INTARRAY [2]); / * || as an adrise put the code in here to print the lists! || 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 contacts 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.rase (list1.begin ()); // Erase the first element (1) using an itrator List1.rase (List1.begin ), list1.end ()); // Erase All the remaining elements cout << "list contacts" << list1.size () << "Elements" << Endl;} output is: List contacts 0 Elements --- -------------------------------------------------- --------------------------- Use the List member function remove () 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 ("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 -------------- -------------------------------------------------- -------------------- Using STL General Algorithm Remove () Remove Element Universal Algorithm from LIST to work differently. 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 :: item new; birds.push_back ("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 past 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;} Output results will be: Original List Cockatoo Galah Cockatoo Rost Cockatoo Galah Cockatoo Rosella King Parrot List According to New Past T End itrator Galah Rosella King Parrot 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) == "-";}}; 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> iprameters 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); if (! 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 ()); if (! Filenames.empty ()) {cout << "Files Specified (in Order) WERE: << Endl; for_each (filenames.begin (), filenames.end () } Else {cout << "no files were specified" << end1;} // check if the help flag WAS specified if (find_if) Flags.begin (), Flags.end (), ishelpflag ())! = Flags.end ()) {cout << "The help flag ws specified" << end1;} // open the files and do wherever you do } Give 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 Simply 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.