Standard Template Library Quick Reference...list or A doubly-link list container that uses...

36
Standard Template Library Quick Reference Containers Containers are general-purpose template classes that are designed to store objects of almost any type. They are useful by themselves, but become even more powerful when combined with other concepts such as iterators and algorithms. Standard Containers Name Header Description vector<T, Alloc> <vector> or <vector.h> Acts very similar to a standard array that can grow to accommodate additional elements. deque<T, Alloc> <deque> or <deque.h> This is a double-ended queue which is efficient at adding or removing elements from either the beginning or end of the queue. list<T, Alloc> <list> or <list.h> A doubly-link list container that uses pointers to nodes. One pointer stores the location of the next node and the second pointer stores the location of the previous node. Faster than the vector and deque containers at some operations, notably adding or removing elements from the middle of the container. NOTE: The Alloc parameter allows you to define your own custom memory allocator if needed. A custom memory allocator is useful is some situations such as when working with embedded systems which do not have general-purpose malloc/free or new/delete operators. Container Operation Costs Operation C-Array vector deque list Insert/erase at start N/A linear constant constant Insert/erase at end N/A constant constant constant Insert/erase in middle N/A linear linear constant Access first element constant constant constant constant Access last element constant constant constant constant Access middle element constant constant constant linear

Transcript of Standard Template Library Quick Reference...list or A doubly-link list container that uses...

  • Standard Template Library Quick Reference

    Containers

    Containers are general-purpose template classes that are designed to storeobjects of almost any type. They are useful by themselves, but become evenmore powerful when combined with other concepts such as iterators andalgorithms.

    Standard Containers

    Name Header Descriptionvector or

    Acts very similar to a standard array thatcan grow to accommodate additionalelements.

    deque or

    This is a double-ended queue which isefficient at adding or removing elementsfrom either the beginning or end of thequeue.

    list or A doubly-link list container that usespointers to nodes. One pointer stores thelocation of the next node and the secondpointer stores the location of the previousnode. Faster than the vector and dequecontainers at some operations, notablyadding or removing elements from themiddle of the container.

    NOTE: The Alloc parameter allows you to define your own custom memoryallocator if needed. A custom memory allocator is useful is some situations suchas when working with embedded systems which do not have general-purposemalloc/free or new/delete operators.

    Container Operation Costs

    Operation C-Array vector deque listInsert/erase at start N/A linear constant constantInsert/erase at end N/A constant constant constantInsert/erase in middle N/A linear linear constantAccess first element constant constant constant constantAccess last element constant constant constant constantAccess middle element constant constant constant linear

  • Operation C-Array vector deque listOverhead none low medium high

    Vector Advantages

    – Vectors can be dynamically resized; when you run out of space it automaticallygrows

    – Elements of a vector can be added or removed from the interior without needingto write custom code

    – You can quickly access the start the or end of the vector, without knowing itsize in advance

    – You can iterate forward or backward through a vector– It is a simple matter to add bounds checking for both operator[] and pointer

    dereferencing– Objects in a vector can be stored in any kind of memory with the help of a

    custom allocator– Unlike standard arrays, vector have usable assignment and comparison

    operators.

    Vector Disadvantages

    – Most implementations have to store a total of 3 memory pointers, compared toone pointer for a standard C-style dynamically allocated array. This does useup very much extra memory, so it is usually not a great burden.

    – A vector will never release memory, even when the number of elements in thevector is reduced.

    Deque Advantages

    – Since a deque acts a lot like a vector, it has the same advantages as using avector when compared to standard C-style arrays

    – It can grow in either direction (front or back) equally well– It is often faster than a vector when the container needs to grow to hold new

    elements

    Deque Disadvantages

    – The operator[] is not as fast as vector's operator[], although it is still pretty fast– Iterating over a deque is also slower than iterating over a vector

    List Advantages

    – Very fast element insertion/removal in the middle of the list– Implements its own memory management system which actually can be helpful

  • on some platforms

    List Disadvantages

    – No random access iterator (which means no operator[])– Uses extra memory to track next/previous node pointers (lists are best used for

    large structure, not small data elements list a character)

    General Guideline

    Use a vector whenever possible since it has the lowest overhead and bestoverall performance. However, if you are going to add and removing items fromthe middle of the collection often, then consider using a list. Use a dequewhenever you will be inserting elements at the head or end most of the time, butvery seldom from the middle of the collection.

    Container Adapters

    The following containers are specialized containers that use one of the standardcontainers to actually store the elements they manage. Basically they arewrappers around one of the standard container templates that provide a restrictedset of operations.

    Container Header Descriptionstack

    or Implements a standard LIFO (Last-In, First-Out) container. You willprobably use the push() and pop()members most often.

    Queue

    or Implements a standard FIFO (First-In, First-Out) container. Thiscontainer does not allow iteration.You will probably use the push() andtop()/pop() members most often.

    priority_queue or This container implements a FIFO,with one small difference. Thelargest element is always the firstitem returned by the top() and pop()methods.

    Associative Containers

    An associative containers stores objects based on key values.

  • Container Header Descriptionset

    or This container holds a uniquecollection of objects in sortedsequence. The Compareparameter defines thefunction/functor to use forcomparing the objects (default isless) and the Allocparameter is for a custom memoryallocator.

    multiset

    or This container holds a collectionof objects in sorted sequence.Unlike a standard set, this typeof container allows duplicate keys.

    map

    or Similar to a set container,except the key is distinct from thedata being stored. Internally amap stores pairelements, organized by Keyvalues. The pair is a helpertemplate. All Key values must beunique.

    map

    or Works like the standard maptemplate, except duplicate Keyvalues are allowed.

  • Iterators

    The standard template library makes heavy use of iterators, which basically actslike pointers. They are used to indicate a position within a collection of elementsand are most often used to process a range of elements.

    Iterator Categories

    Iterator Category DescriptionInput Iterator This type of iterator allows you to read the element

    it references. It does not allow you to change theelement.

    Output Iterator This type of iterator grants permission to write anelement, but does not guarantee read access isavailable (although it may allow reading theelement also.)

    Forward Iterator A forward iterator generally supports both Input andOutput operations, unless the iterator is constant,which restricts its usage to reading only. Thedifference between a Forward iterator and an Inputor Output iterator is that Forward iterators canusually be used with multi-pass algorithms.

    Bidirectional Iterator This is very similar to a Forward iterator, except itcan be both incremented and decremented. Not allof the container templates support Bidirectionaliterators.

    Random Access Iterators This type of iterator supports incrementing,decrementing and also adding and subtractingarbitrary offsets, subscripting and more. They actmuch more like traditional pointers than the otheriterators.

    Concrete Iterator Template Classes

    Iterator Class Descriptionistream_iterator Reads objects of type T from an input stream

    (such as cin). Stops when it reaches the end ofthe stream. Used often with the copy()algorithm.

    ostream_iterator Writes objects of type T to an output streams(such as cout). Used often with the copy()algorithm.

  • Iterator Class Descriptionreverse_iterator

    This iterator reverses the meaning of theincrement (++) and decrement (--) operators.

    insert_iterator This iterator is used to insert objects into acontainer. It will track of the next point ofinsertion and advance automatically whenever anew element is inserted.

    front_insert_iterator

    This iterator class is an output iterator thatalways inserts new elements at the front of thecontainer. The FrontInsertSequence means youcan only use this type of iterator with containersthat have the front(), push_front() andpop_front() methods. Primarily this includesthe deque and list template classes.

    back_insert_iterator

    This iterator class is an output iterator thatalways appends new elements at the end of acontainer. The BackInsertionSequence meansyou can only use this type of iterator withcontainers that have the back(), push_back()and pop_back() methods. Primarily thisincludes the vector, list and dequetemplate classes.

  • Algorithms

    The Standard Template Library also includes a large number of template functionscollectively referred to as algorithms. The combination of the container classeswith the algorithm template functions provides C++ with many advanced andpowerful constructs.

    Algorithm Types

    Algorithm Type DescriptionNon-mutating Algorithms in this category are used to process

    and/or search a container, but never modify thecontainer's elements.

    Mutating Algorithms in this category are used to modifycontainers in some way.

    Sorting There are a number of algorithms available forsorting, searching and merging containers and theirelements.

    Generalized Numeric These types of algorithms are used to perform somekind of mathematical operation against elements in acontainer.

    Non-Mutating Algorithms

    Remember, the non-mutating algorithms never modify the containers they areworking on.

    Algorithm DescriptionUnaryFunctionfor_each( InputIterator first, InputIterator last, UnaryFunction f)

    Iterates all of the elements fromfirst to last and calls function fonce per element. The returnvalue is sometimes useful whendealing with functors.

    InputIteratorfind( InputIterator first, InputIterator last, const EqualityComparable& value)

    Attempts to locate value in theelements pointed to by first andlast. The value is usually thesame type as the elements in thecontainer, but conversions areperformed if needed. Returns aniterator that points to the firstmatch if found. Returns last if theitem cannot be found.

  • Algorithm DescriptionInputIteratorfind_if(InputIterator first, InputIterator last, Predicate pred)

    Similar to the find() algorithm,except instead of comparingvalues directly, it passes eachelement in the range to a helperfunction (or functor) that tests theobject in some way and returns aboolean value. If the helperfunction returns true, the searchstops and an iterator to theelement is returned, otherwise lastis returned.

    ForwardIteratoradjacent_find( ForwardIterator first, ForwardIterator last)

    ForwardIteratoradjacent_find( ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred )

    This function iterates over thecontainer's elements to locate thefirst of 2 iterators that are valid.The first version is not very useful,the second works like find_if() soyou can call a custom function (orfunctor) that tests adjacentelements and returns a boolean.

    InputIteratorfind_first_of( InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2)

    InputIteratorfind_first_of( InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate comp)

    Similar to using find(), except thisalgorithm searches the firstsequence to find any element thatis also in a second sequence.

    The second version of the functionallows you to use a customfunction (or functor) instead of thestandard operator==().

  • Algorithm Descriptioniterator_traits::difference_typecount( InputIterator first, InputIterator last, const EqualityComparable& value)

    voidcount( InputIterator first, InputIterator last, const EqualityComparable& value, Size& n )

    This algorithm iterators over asequence and counts the numberof elements that match the givenvalue.

    The first version returns thenumber of matches found, whilethe second version adds thenumber of matches to the valuereferenced by n.

    The second version is deprecatedand may be removed later.

    iterator_traits::difference_typecount_if( InputIterator first, InputIterator last, Predicate pred)

    voidcount_if( InputIterator first, InputIterator last, Predicate pred, Size& n)

    Similar to the count() algorithm,but instead of comparing theelements to some value, passeseach element to a helper function(or functor) and only countselements where the helperfunction returns true.

    The second version is deprecatedand may be removed later.

    pairmismatch( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )

    pairmismatch( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred )

    Searches the sequencereferences by first1 and last1 tofind an element that does notmatch the elements in first2. Inother words, finds the firstdifference between 2 containers.

    The second versions of thealgorithm allows you to use acustom function (or functor) tocompare the elements in thecontainers.

  • Algorithm Descriptionboolequals( InputIterator first1, InputIterator last1, InputIterator2 first2 )

    boolequals( InputIterator first1, InputIterator last1, InputIterator2 first2, BinaryPredicate binary_pred )

    Similar to the mismatch()algorithm, except this algorithmsimply returns true or false toindicate whether the 2 sequencesare equal or not.

    Can also be done using:mismatch(f1,l1,f2).first == l1

    ForwardIterator1search( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2 )

    ForwardIterator1search( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate binary_pred )

    These algorithms attempt to findthe sequence first2->last2somewhere instead the sequencefirst1->last1.

    This works a bit like searching fora substring within a larger string,except of course the elements canbe of any type, not just characters.

    ForwardIteratorsearch_n( ForwardIterator first, ForwardIterator last, Integer count, const T& value )

    ForwardIteratorsearch_n( ForwardIterator first, ForwardIterator last, Integer count, const T& value, BinaryPredicate binary_pred )

    Attempts to find the position in thesequence where value is repeatedcount times in a row. Useful fortesting for repeated elements.

    NOTE: Using 0 for count willalways succeed, no matter thevalue, since there will be nocomparisons performed.

  • Algorithm DescriptionForwardIterator1find_end( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first1, ForwardIterator2 last2 )

    ForwardIterator1find_end( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate binary_pred )

    Works similar to search().Probably should be namedsearch_end().

    Instead of returning the first matchin the search, this algorithmreturns an iterator that points tothe last match instead.

    Mutating Algorithms

    The mutating algorithms are used to make changes to containers or the elementsinside a container.

    Algorithm DescriptionOutputIteratorcopy( InputIterator first, InputIterator last, OutputIterator result )

    This algorithm copies theelements referenced by first->lastby overwriting the elements inresult.NOTE; The output container mustbe large enough to hold all thecopied elements, since thisalgorithm assigns the copiedelements, it does not push them.

    BidirectionalIterator2copy_backward( BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result )

    Also copies the elements fromfirst->last into the container atresult, but copies from last to firstin backward sequence.

    NOTE: result must point to theend of the sequence, not thebeginning.

    void swap( Assignable& a, Assignable& b ) Assigns a to b and b to a.

  • Algorithm Descriptionvoid swap_iter( ForwardIterator1 a, ForwardIterator2 b )

    Same as swap( *a, *b ).

    ForwardIterator2swap_ranges( ForwardIterator1 first1, ForwardIterator2 last1, ForwardIterator2 first2 )

    Swaps all the elements pointed toby first1->last1 with the elementspointed to by first2.

    OutputIteratortransform( InputIterator first, InputIterator last, OutputIterator result, UnaryFunction op )

    OutputIteratortransform( InputIterator1 first1, InputIterator1 last1, InputIterator1 first2, OutputIterator result, BinaryFunction binary_op )

    This is similar to the copy()algorithm, except before theelements are copied into the newcontainer, a helper function (orfunctor) is called that can change(transform) the elements in someway.The second version allows you todo that same thing, except in thiscase you are extracting elementsfrom 2 different containers andcombining them into one resultcontainer, by calling a helperfunction that receives oneelement from each inputcontainer.

    voidreplace( ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value )

    Replaces every element withvalue old_value, with the valuenew_value in the sequence first->last.

    voidreplace_if( ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value )

    Similar to replace(), exceptinstead of comparing each inputelement against a value, calls ahelper function (or functor). If thehelper function returns true, theelement will be replaced bynew_value.

  • Algorithm Descriptionvoidreplace_copy( InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value )

    Copies all the elements into anew container, but replaces anyelements with old_value withnew_value if found during thecopy process.

    voidreplace_copy_if( InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value )

    Works like replace_copy(),except only replaces elementswith new_value if the helperfunction (or functor) returns true.

    voidfill( ForwardIterator first, ForwardIterator last, const T& value )

    Use this algorithm to quicklyassign value to the elementsreferenced by first->last.

    OutputIteratorfill_n( OutputIterator first, Size n, const T& value )

    This algorithm also assigns valueto the elements referenced byfirst. It does this n times.

    voidgenerate( ForwardIterator first, ForwardIterator last, Generator gen )

    This algorithm calls the helperfunction (or functor) gen andstores the results in eachelement referenced by first->last.

    voidgenerate_n( OutputIterator first, Size n, Generator gen )

    Calls the helper function (orfunctor) gen and assigns theresults to the iterator first, exactlyn times.

  • Algorithm DescriptionForwardIteratorremove( ForwardIterator first, ForwardIterator last, const T& value )

    Removes all elements with valuefrom the sequence referenced byfirst->last.

    ForwardIteratorremove_if( ForwardIterator first, ForwardIterator last, Predicate pred )

    Same as remove(), except callsthe helper function (or functor)pred to determine whether or notto remove the item. The helperfunction returns true when theelement should be removed.

    OutputIteratorremove_copy( InputIterator first, InputIterator last, OutputIterator result, const T& value )

    Copies elements in first->last toresult if they do not equal value.

    OutputIteratorremove_copy_if( InputIterator first, InputIterator last, OuputIterator result, Predicate pred )

    Calls the helper function (orfunctor) pred for each element infirst->last and copies the elementto result if pred returns false. Inother words, true elements arenot copied.

    ForwardIteratorunique( ForwardIterator first, ForwardIterator last )

    ForwardIteratorunique( ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred )

    Removes duplicate elementsfrom the sequence first->last sowhen completed, only uniqueelements remain. The secondflavor uses a helper function (orfunctor) to decide if elements areunique or not.

  • Algorithm DescriptionOutputIteratorunique_copy( InputIterator first, InputIterator last, OutputIterator result )

    OutputIteratorunique_copy( InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate binary_pred )

    Copies only unique elements(skips consecutive duplicates)from first->last into result. Worksbest when the input container issorted.

    voidreverse( BidirectionalIterator first, BidirectionalIterator last )

    Reverses a container so the lastelement becomes the first andthe first element becomes thelast and so on.

    OutputIteratorreverse_copy( BidirectionalIterator first, BidirectionalIterator last, OutputIterator result )

    Copies elements first->last intocontainer result, in reversesequence.

    ForwardIteratorrotate( ForwardIterator first, ForwardIterator last, ForwardIterator middle )

    Rearranges the container somiddle becomes first and lastbecomes middle. This meansfirst also becomes middle+1.Acts like rotating a circle.

    OutputIteratorrotate_copy( ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result )

    Works like rotate(), exceptcopies the rotated elements intoresult. Faster then doing a copy() followed by a rotate().

    voidrandom_shuffle( RandomAccessIterator first, RandomAccessIterator last )

    voidrandom_shuffle( RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& rand )

    Randomly rearranges all theelements in first->last. Thesecond version allows you to usea custom random numbergenerator functor.

  • Algorithm DescriptionRandomAccessIteratorrandom_sample( InputIterator first, InputIterator last, RandomAccessIterator ofirst, RandomAccessIterator olast )

    RandomAccessIteratorrandom_sample( InputIterator first, InputIterator last, RandomAccessIterator ofirst, RandomAccessIterator olast, RandomNumberGenerator& rand )

    Works like the random_shuffle()algorithm, except instead ofrearranging the input container,copies the elements randomlyinto another container. Eachinput element will only appearonce in the output, in randomsequence.

    Again a custom random numbergenerator can be used if needed.

    OutputIteratorrandom_sample_n( ForwardIterator first, ForwardIterator last, OutputIterator out, Distance n )

    OutputIteratorrandom_sample_n( ForwardIterator first, ForwardIterator last, OutputIterator out, Distance n, RandomNumberGenerator& rand )

    Similar to random_sample(),except this algorithm stops aftercopying n elements. Thisalgorithm preserves the relativeorder of the copied elements.

    ForwardIteratorpartition( ForwardIterator first, ForwardIterator last, Predicate pred )

    This algorithm rearranges theelements in first->last by callingthe helper function (or functor)pred against each element. Allelements where pred returns trueare placed before the elementsthat return false. The returnediterator will point to the middle.(i.e. The first false element.)

  • Algorithm DescriptionForwardIteratorstable_partition( ForwardIterator first, ForwardIterator last, Predicate pred )

    Same as partition(), except theelements will maintain theirrelative order within thesequence.

    Sorting Algorithms

    This group of algorithm are used to fully or partially sort the elements in acontainer.

    Algorithm Descriptionvoidsort( RandomAccessIterator first, RandomAccessIterator last )

    voidsort( RandomAccessIterator first, RandomAccessIterator last, Compare comp )

    Rearranges the container so theelements are in sorted sequence.By default, it uses operator

  • Algorithm Descriptionvoidpartial_sort( RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last )

    voidpartial_sort( RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare comp )

    This algorithm also sortselements in containers, but in thiscase only elements from first->middle are sorted and placed atthe beginning of the container.The elements from middle->lastare unsorted (and probablyrearranged).

    RandomAccessIteratorpartial_sort_copy( InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last )

    RandomAccessIteratorpartial_sort_copy( InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, Compare comp )

    This algorithm combines partialsorting with copying of theelements. It will stop whenever itprocesses (last-first) or(result_last-result_first) elements,whichever is smaller.

    Useful for extracting X number ofitems (perhaps the smallest orlargest values) from a largecontainer into a smaller one.

    boolis_sorted( ForwardIterator first, ForwardIterator last )

    boolis_sorted( ForwardIterator first, ForwardIterator last, Compare comp )

    Returns true if the range isalready sorted, false otherwise.

  • Algorithm Descriptionvoidnth_element( RandomAccessIterator first, RanomAccessIterator nth, RandomAccessIterator last )

    voidnth_element( RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp )

    This is a special kind of partialsort that ensures elements to theleft of nth are less than allelements to the right of nth. Theleft side may or may not besorted. The same applies to theright side. However, all items tothe left will be less than the itemsto the right, with nth used as asplit point.

    Searching Algorithms

    Algorithm DescriptionForwardIteratorlower_bound( ForwardIterator first, ForwardIterator last, const T& value )

    ForwardIteratorlower_bound( ForwardIterator first, ForwardIterator last, const T& value, Compare comp )

    This algorithm performs a fastbinary search of a sortedcontainer and returns the iteratorwhere a new element of valuecan be inserted to maintain theproper order of elements.Uses operator

  • Algorithm Descriptionpairequal_range( ForwardIterator first, ForwardIterator last, const T& value )

    pairequal_range( ForwardIterator first, ForwardIterator last, const T& value, Compare comp )

    Combines using lower_bound()and upper_bound() into a singlealgorithm that returns bothiterators in a single function call.NOTE: The first version onlyrequires that value becomparable to elements of typeT.

    boolbinary_search( ForwardIterator first, ForwardIterator last, const T& value )

    boolbinary_search( ForwardIterator first, ForwardIterator last, const T& value, Compare comp )

    Compares each element in first->last against value using eitherthe default comparison operatoror a custom comparison function(or functor) comp and returnstrue if found, false otherwise.NOTE: Since you will often needto know the position of theelement, most of the time youshould consider usinglower_bound(), upper_bound(),or equal_range() instead.

    Merging Algorithms

    There are a couple of algorithms you can use for combining and merging sortedcontainers together.

  • Algorithm DescriptionOutputIteratormerge( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result )

    OutputIteratormerge( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp )

    Combines 2 sorted containers(first1->last1 and first2->last2)into another container (result) sothat the output container is alsosorted. The merge is stable,which means the relative order ofduplicate elements is preserved.

    voidinplace_merge( BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last )

    voidinplace_merge( BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp )

    This algorithm takes a containerthat has been partially sorted(split around middle) andcompletes the sort so the entirecontainer is now sorted.

    Set Algorithms

    There are also a set of algorithms designed specifically for performing setoperations. Most of these algorithms do not require a set container, but theymay be used to implement the set template class.

  • Algorithm Descriptionboolincludes( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2 )

    boolincludes( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp )

    Tests 2 sorted ranges todetermine if all of the elements infirst2->last2 are also found infirst1->last1. Returns true only ifall of the elements in the secondcontainer can be found in the firstcontainer.Both input containers must besorted for this algorithm to workproperly.

    OutputIteratorset_union( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result )

    OutputIteratorset_union( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp )

    Copies all the sorted elementsthat are in either first1->last1 orfirst2->last2 into a new container(result), while preserving the sortsequence.Both input containers must besorted for this algorithm to workproperly.NOTE: If the same valueelements appear in bothcontainers, then this algorithmcopies the elements from thecontainer where the value isrepeated the most often.

  • Algorithm DescriptionOutputIteratorset_intersection( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result )

    OutputIteratorset_intersect( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp )

    Copies all the sorted elementsthat are found in both first1->last1 and first2->last2 into anew container (result), whilepreserving the sort sequence.Both input containers must besorted for this algorithm to workproperly.NOTE: If the same valueelements appear in bothcontainers, then this algorithmcopies the elements from thecontainer where the value isrepeated the least often.

    OutputIteratorset_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result )

    OutputIteratorset_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp )

    Copies all the sorted elementsthat are in first1->last1 but arenot in first2->last2 into a newcontainer (result), preserving thesort sequence.Both input containers must besorted for this algorithm to workproperly.

  • Algorithm DescriptionOutputIteratorset_symmetric_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result )

    OutputIteratorset_symmetric_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp )

    Copies all the sorted elementsthat are in first1->last1 but not infirst2->last2 as well as all theelement in first2->last2 that arenot in first1->last1 into a newcontainer (result), preserving thesort sequence. After using thisalgorithm the output container willhave the set of elements that arenot found in both inputcontainers.Both input containers must besorted for this algorithm to workproperly.

    Heap Operations

    A heap is data structure similar to a tree, but normally stores its elements as anarray (including vector and deque). The difference is that in a heap not everyelement has to be perfectly sorted. Instead the elements have to arranged so thehighest value is always above the lower values. This is used by thepriority_queue template internally to arrange elements by value.

    Algorithm DescriptionVoidmake_heap( RandomAccessIterator first, RandomAccessIterator last)

    voidmake_heap( RandomAccessIterator first, RandomAccessIterator last, Compare comp )

    Turns the container first->last into aheap. Typically the underlyingcontainer will be a C-style array,vector or deque object.

  • Algorithm Descriptionvoidpush_heap( RandomAccessIterator first, RandomAccessIterator last )

    voidpush_heap( RandomAccessIterator first, RandomAccessIterator last, Compare comp )

    This function moves an elementthat has already been added to theend of a container into its properlocation within the heap structure.You must add the element to theunderlying container yourself,perhaps by using the push_back()function.

    voidpop_heap( RandomAccessIterator first, RandomAccessIterator last )

    voidpop_heap( RandomAccessIterator first, RandomAccessIterator last, Compare comp )

    This method removes the largestelement from the heap structure(the largest element is normally thefirst element). It does not actuallyremove the element, but insteadmoves it to the end of theunderlying container andreorganizes the remainingelements so the heap is still valid.

    voidsort_heap( RandomAccessIterator first, RandomAccessIterator last )

    voidsort_heap( RandomAccessIterator first, RandomAccessIterator last, Compare comp )

    Returns the heap's underlyingheap sequence back into a sortedsequence. The relative order ofthe elements is not guaranteed tobe preserved.

    boolis_heap( RandomAccessIterator first, RandomAccessIterator last )

    boolis_heap( RandomAccessIterator first, RandomAccessIterator last, Compare comp )

    Tests a container to determine if itis already organized into thesequence needed to be treated asa heap structure.

    Miscellaneous Algorithms

    Here are several general-purpose algorithms.

  • Algorithm Descriptionconst T&min( const T& a, const T& b )

    const T&min( const T& a, const T& b, Compare comp )

    Compares a to b and returns theone with the lesser value (returns aif they are equal). Uses operator<by default.

    const T&max( const T& a, const T& b )

    const T&max( const T& a, const T& b, Compare comp )

    Compares a to b and returns theone with the greater value (returnsa if they are equal). Usesoperator< by default.

    ForwardIteratormin_element( ForwardIterator first, ForwardIterator1 last )

    ForwardIteratormin_element( ForwardIterator first, ForwardIterator last, Compare comp )

    Finds the smallest element in thecontainer and returns an iteratorthat references that element.

    ForwardIteratormax_element( ForwardIterator first, ForwardIterator1 last )

    ForwardIteratormax_element( ForwardIterator first, ForwardIterator last, Compare comp )

    Finds the largest element in thecontainer and returns an iteratorthat references that element.

  • Algorithm Descriptionboollexicographical_compare( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2 )

    boollexicographical_compare( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp )

    While this algorithm's name isawkward, the job it performs issimple. It compares elements oneby one from both containers until iteither reaches the end or findselements that do not match. If bothcontainers stored exactly the sameelements in the same sequence, itreturns true, otherwise it returnsfalse.

    boolnext_permutation( BidirectionalIterator first, BidirectionalIterator last )

    boolnext_permutation( BidirectionalIterator first, BidirectionalIterator last, Compare comp )

    This algorithm is used to rearrangethe elements in a sorted containerin every other possible sequence(or permutation). Every time youcall this algorithm, the elements willbe reordered and it will return true.Once all the permutations havebeen generated, the elements arereturned to the original sortedsequence and false is returned.

    boolprev_permutation( BidirectionalIterator first, BidirectionalIterator last )

    boolprev_permutation( BidirectionalIterator first, BidirectionalIterator last, Compare comp )

    This algorithm is the mirror imageof next_permutation().

  • Algorithm DescriptionTaccumulate( InputIterator first, InputIterator last, T init )

    Taccumulate( InputIterator first, InputIterator last, T init, BinaryFunction binary_op )

    Adds all the elements from first->last to init and returns the sum.The second version allows you touse a function (or functor) that willbe called with the previous result(initially the same as init) and thenext element in the container. Thefunction will return a value of type Tthat will be added to the nextresult.NOTE: Defined in the header.

    Tinner_product( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init )

    Tinner_product( InputIterator1 first1, InputIterator1 last1, InputIterator2 first1, T init, BinaryFunction1 binary_op1, BinaryFunction2 binary_op2 )

    This algorithm takes each elementin the first container (first1->last1)and multiplies it by eachcorresponding element in thesecond container (first2) andreturns the sum of all of the results+ the value in init. Think of it as acrude matrix multiply and addoperation.NOTE: Defined in the header.

    OutputIteratorpartial_sum( InputIterator first, InputIterator last, OutputIterator result )

    OutputIteratorpartial_sum( InputIterator first, InputIterator last, OutputIterator result, BinaryOperator binary_op )

    This algorithm visits each elementin a container and adds theelement's value to the nextelement's value and stores theresult in the output container. Thefirst element is always just copiedto the output.

    Output[0] = Input[0]Output[i] = Input[i-1] + Input[i]

  • Algorithm DescriptionOutputIteratoradjacent_difference( InputIterator first, InputIterator last, OutputIterator result )

    OutputIteratoradjacent_difference( InputIterator first, InputIterator last, OutputIterator result )

    Copies the first element from firstto result. Next, subtracts allelements from the previouselement and stores the result inresult.

    Output[0] = Input[0]Output[i] = Input[i] – Input[i-1]

  • Function Objects (aka Functors)

    A function object or functor is any object that can be used as if it were a plain oldfunction. A class can used as a functor if it defines operator(), which issometimes referred to as the default operator. So a functor is really either apointer to a static function, or a pointer to an object that defines operator(). Theadvantages of using a function object should become apparent soon.

    Many of the algorithms in the Standard Template Library will accept a functor touse instead of the default functor defined by the template class. This allows theuser of the algorithm to adapt the algorithm to their specific needs. You can usethe predefined function objects that are included with the STL, or you can roll yourown as long as your functors have the required function signatures.

    There are 3 major types of function objects and several other less commonly usedfunction objects.

    Major Functor Types

    Functor Type Used By DescriptionPredicate (Unaryor Binary)

    Unary: remove_if, find_if,count_if, replace_if,replace_copy_if, remove_if, andremove_copy_ifBinary: adjacent_find,find_first_of, mismatch, equal,search, search_n, find_end,unique, and unique_copy

    A predicate function objectreturns a bool value of trueor false. Generally they willreceive one argument oftype T, but some algorithmswill require a binarypredicate function whichtakes in two arguments oftype T and returns a bool.

    ComparisonFunctions

    sort, stable_sort, partial_sort,partial_sort_copy, is_sorted,nth_element, lower_bound,upper_bound, equal_range,binary_search, merge,inplace_merge, includes,set_union, set_intersection,set_difference,set_symmetric_difference,make_heap, push_heap,pop_heap, sort_heap, is_heap,min, max, min_element,max_element,lexicographical_compare,next_permutation andprev_permutation

    This kind of function objecttakes two arguments of typeT and return true or falseafter the items have beencompared. The operator<is an example of this kind offunction and is generally thedefault used when you donot supply your ownfunction object.

  • Functor Type Used By DescriptionNumericFunctions (Unaryor Binary)

    Unary: for_each and transformBinary: transform, accumulate,and inner_product

    This kind of function willgenerally accept either oneor two arguments of type Tand returns the results ofsome sort of mathematicaloperation. The accumulatealgorithm uses operator+as its default numericfunction.

    Here is an example of an algorithm that uses a function.

    #include #include #include #include

    using namespace std;

    bool failingGrade( int score ){

    return score < 70;}

    int main( int argc, char *argv[] ){

    vector scores;

    scores.push_back( 69 );scores.push_back( 70 );scores.push_back( 85 );scores.push_back( 80 );

    cout

  • Here is a better version that uses a function object (object of a class with anoperator() defined).

    #include #include #include #include

    using namespace std;

    class Failing{private: int cutoff;public: Failing( int below ) : cutoff(below) {} bool operator()( int score ) { return score < cutoff; }};

    int main( int argc, char *argv[] ){

    vector scores;

    scores.push_back( 69 );scores.push_back( 70 );scores.push_back( 85 );scores.push_back( 80 );

    cout

  • class Failing{private: T cutoff;public: Failing( T below ) : cutoff(below) {} bool operator()( T const& score ) { return score < cutoff; }};

    int main( int argc, char *argv[] ){

    vector scores;

    scores.push_back( 69 );scores.push_back( 70 );scores.push_back( 85 );scores.push_back( 80 );

    cout

  • Predefined Function Objects

    Since using function objects with algorithms is so common, a number ofpredefined function objects are available for you to use in your code.

    Arithmetic Function Objects

    Functor Type Descriptionplus Binary Adds two elements together to calculate a

    sum.minus Binary Subtracts two elements to calculate the

    difference.multiplies** times in olderversions of STL

    Binary Multiples two elements to calculate aproduct.

    divides Binary Divides one element by another to calculatea dividend.

    modulus Binary Performs a modulo operation against twoelements and calculates the remainder.

    negate Unary Negates the element so positive valuesbecome negative and vice-versa.

    Comparison Function Objects

    Functor Type Descriptionequal_to Binary Compares two elements for equality using

    operator==.not_equal_to Binary Compares two elements for inequality using

    operator==.less Binary Compares two elements using operator.less_equal Binary Compares two elements using operator=.

    Logical Function Objects

    Functor Type Descriptionlogical_and Binary Performs an AND operation with two other

    conditions.

  • Functor Type Descriptionlogical_or Binary Performs an OR operation with two other

    conditions.logical_not Unary Inverts boolean logic.

    Function Object Adapters

    Alas the function objects listed above are quite useful, but limited in scope. Thereis no apparent way you can use functors like less with any algorithm thatrequires a unary function, or is there?

    This is the concept of a Function Object Adapter. They can be used to convertbinary functors into unary functors or to do other conversions such as converting aplain function into a function object or converting a class member function backinto a standard function so it can be used with the algorithms.

    Adapter Description Notesbinder1st Adapts a unary

    function/functor and aconstant into a binaryfunctor, where the constantwill be used as the firstargument to the functor.

    Don't use directly. Insteaduse the bind1st() function,which creates a binder1stobject internally.

    binder2nd Adapts a unaryfunction/functor and aconstant into a binaryfunctor, where the constantwill be used as the secondargument to the functor.

    Don't use directly. Instead,use the bind2nd() function,which creates a binder2ndobject internally.

    ptr_fun Converts a pointer to astandard function into afunction object. Neededwhen trying to customizethe container templates(such as set) whichrequire a functor class anddo not support functionobjects.

    Can be used to convert bothunary and binary functionsinto function objects.

    unary_negate Converts a unary predicatefunction object by invertingthe logical return value.

    Don't use directly. Use thenot1() function instead.

    binary_negate Converts a binary predicatefunction object by invertingthe logical return value.

    Don't use directly. Use thenot2() helper functioninstead.

  • Adapter Description Notesunary_compose Combines multiple function

    objects into a single objectby calling the first functionand passing the results tothe next function. In otherwords, allows you to chainfunction calls together.

    Don't use directly. Use thecompose1() helper functioninstead.

    binary_compose Combines multiple functionobjects into a single objectin the same manner asunary_compose, exceptworks on binary functions.

    Don't use directly. Use thecompose2() helper functioninstead.

    mem_fun Converts a memberfunction of a class (orstruct) into a plain functionso it can be used withalgorithms. It performsopposite from the sameway ptr_fun() does.

    Use this helper functionwhen you are storingpointers to objects in acontainer and want to call amember function of the classin an algorithm.

    mem_fun_ref Converts a memberfunction of a class (ortemplate) into a functionobject just like themem_fun() functionadapter does.

    Use this helper functionwhen you are storing objects(not pointers) in a containerand need to access theobject by reference.