Vanderbilt Lecture Notes: STL Algorithms PDF

Summary

This document is a lecture that provides a synopsis of STL algorithms within the context of software design. It outlines different categories of algorithms and explains their uses.

Full Transcript

Lecture 19 - STL Algorithms CS 3251 Intermediate Software Design Prof. Graham Hemingway STL Algorithms Agenda: STL Algorithm Overview Basic Algorithm Familiarization Adaptation & Composition Functors Containers Iterators Functions STL Recap STL Algorith...

Lecture 19 - STL Algorithms CS 3251 Intermediate Software Design Prof. Graham Hemingway STL Algorithms Agenda: STL Algorithm Overview Basic Algorithm Familiarization Adaptation & Composition Functors Containers Iterators Functions STL Recap STL Algorithms Algorithms operate over iterators, not containers Each container declares an iterator and a const iterator as a trait vector and deque declare random access iterators list, map, set, multimap, and multiset declare bidirectional iterators Containers declare factory methods for its iterator type: begin(), end(), rbegin(), rend() Composing an algorithm with a container is done by invoking the algorithm with iterators for that container Templates provide compile-time type safety for combinations of containers, iterators, and algorithms STL Algorithms The primary categories of STL algorithms are: Non-mutating: operate using a range of iterators, but do not change the data elements found e.g., count(), equal(), find(), search() Mutating: operate using a range of iterators, but can change the order of the data elements e.g., copy(), remove(), fill(), replace(), rotate() Sorting and sets: sort or search ranges of elements and act on sorted ranges by testing values e.g., sort(), nth_element(), binary_search() Numeric: algorithms that produce (generally) numeric results e.g., min(), min_element(), next_permutation() Bene ts of STL Algorithms STL algorithms are decoupled from the particular containers they operate on and are instead parameterized by iterators. All containers with the same iterator type can use the same algorithms. Since algorithms are written to work on iterators, the software development e ort is drastically reduced. e.g., Instead of writing a search routine for each type of container, only write one for each iterator type and apply it any container. fi ff STL Algorithms Speci c algorithms exist within each type that accept certain conditions based on the su x: Predicate names end with the _if su x They require an “if” predicate test function as an argument. This function must return either true or false Functor calls may be substituted for the test function Predicate names end with the _n su x Iterate a xed number of times, instead of over a range. Typically means the rst param is an iterator, but the second param is an integer value fi fi fi ffi ffi ffi STL Algorithms for_each() Applies the function object f to each element in the range from rst to last. f’s return value, if any, is ignored. for_each Example fi STL Algorithms Search and Sorting Algorithms find(first, last, value) Returns a forward iterator at the rst element in the sequence range that matches the provided value. find_if(first, last, pred) Returns a forward iterator at the rst element in the sequence range for which the predicate is true. sort() Sorts the elements binary_search() search_sort Example fi fi STL Algorithms Mutating Algorithms copy(), copy_backward() swap(), swap_ranges() replace(), replace_if(), replace_copy(), replace_copy_if() fill(), fill_n() remove(), remove_if() random_shuffle() Etc. mut_algor Example STL Algorithms transform() Scans a range and for each use a function to generate a new object put in a second container or takes two intervals and applies a binary operator to items to generate a new container. transform Example 1 transform Example 2 STL Function Objects Function objects (aka functors) declare & de ne operator() STL provides helper base class templates unary_function and binary_function to facilitate user-de ned function objects. STL provides a number of common-use function object class templates: Arithmetic: plus, minus, times, divides, modulus, negate Comparison: equal to, not equal to, greater, less, greater equal, less equal Logical: logical and, logical or, logical not A number of STL generic algorithms can take STL-provided or user-de ned function object arguments to extend algorithm behavior. func_obj Example fi fi fi STL Adaptors STL adaptors implement the Adaptor design pattern i.e., convert one interface into another interface that clients expect Container adaptors include stack, queue, priority queue Iterator adaptors include reverse_iterators() and back_inserter() Function adaptors include negators and binders STL adaptors can be used to narrow interfaces (e.g., a stack adaptor for vector) STL Container Adaptors Container Adaptors are considered near-containers: They are similar in concept to rst-class containers, but do not provide all of the capabilities of rst-class containers Container Adaptors do not provide the actual data structure implementation into which elements are stored, because adaptors do not support iterators fi fi STL Container Adaptors A stack container adaptor will adapt a vector, list, or deque so that the container will appear as a stack that de nes a LIFO data structure. Permits the use of push() and pop() The queue container adaptor permits the insertion of data at the back of the underlying data structure and deletions from the front of the underlying data structure. The typical FIFO data structure. stack Example queue Example fi STL Container Adapters The priority_queue adaptor provides insertions in sorted order into the data structure and deletions from the front of the data structure. By default this priority_queue is implemented using the vector class Insertions occur such that the highest priority item (for example, the largest value) is inserted at the front of the queue priority_queue Example STL Iterator Adaptors STL algorithms that copy elements are passed an iterator that marks the position within a container to begin copying. e.g., copy(), unique-copy(), copy_backwards(), remove_copy() and replace_copy() With each element copied, the value is assigned and the iterator is incremented. Each copy requires the target container has su cient size to hold the set of assigned elements. Iterator adaptors can be used to expand the containers as the algorithm executes. Begin with an empty container, use the inserter with the algorithms to grow the container as needed. ffi STL Iterator Adaptors: back_inserter() back_inserter() causes the container’s push_back() operator to be invoked in place of the assignment operator The argument passed to back_inserter() is the container itself back_inserter Example STL Function Adaptors STL has prede ned functor adaptors that will change their functions so that they can: Perform function composition and binding Allow fewer created functors These functors permit combining, transforming and manipulating functors with each other, certain values or with special functions STL functor adaptors include Binders (bind, bind1st* and bind2nd*) bind arguments Negators (not_fn, not1* and not2*) adapt functors by negating arguments MemberFun(mem_fn, mem_fun*, mem_fun_ref*) convert a member function into a callable functor *Deprecated fi STL Function Adaptors: Binder A binder can transform a -nary functor into a lesser functor by acting as a converter between the functor and an algorithm. Binders always store both the binary functor and the argument internally The argument is passed as one of the arguments to the functor every time it is called bind(op, args)calls op with “placeholders” for arguments bind1st*(op, arg)calls op with arg as the first parameter. bind2nd*(op, arg)calls op with arg as the second parameter. binder Example *Deprecated STL Function Adaptors: Negator A negator can be used to store the opposite result of a functor not_fn(obj) negates the result of a callable object not1*(op) negates the result of a unary op not2*(op) negates the result of a binary op negator Example *Deprecated STL Function Adaptors: mem_fn A member function and a pointer-to-function adaptor can be used to allow class member functions or C-style functions as arguments to STL prede ned algorithms mem_fn(PtrToMember mf) converts a pointer to member to a functor whose first argument is an instance of the class. mem_fn Example fi Advantages of Using STL There are many bene ts of using the STL: The STL provides a signi cant level of exible functionality The STL provides very good performance at low run-time space costs The STL only uses generalized algorithms when their e ciency is good The STL also provides specialized algorithms: For example, the generic sort algorithm works well on deques and vectors and can also be used for lists,but the e ciency would be poor A special optimized sort algorithm for lists is provided ffi ffi fi fi fl Disadvantages of Using STL As with anything, there are disadvantages of using the STL: Programming with the STL does not increase the safety of the programs Programming with the STL requires time to adjust to the di erences of standard object-oriented programming Containers, iterators, and algorithms ff

Use Quizgecko on...
Browser
Browser