CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair )

Slides:



Advertisements
Similar presentations
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Advertisements

CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
Object Oriented Data Structures
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
1 Iterators Good reference site:
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
ITERATORS. Iterator An iterator in C++ is a concept that refines the iterator design pattern into a specific set of behaviors that work well with the.
Overview of C++ Templates
CS212: Object Oriented Analysis and Design Lecture 28: Functors.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Chapter 8 Writing Generic Functions. Objectives Understand the use of generic functions. Learn about the use of templates, their advantages and pitfalls.
Overview of STL Function Objects
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
C++ Functions A bit of review (things we’ve covered so far)
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Motivation for Generic Programming in C++
Motivation and Overview
Standard Template Library (STL)
The C++ Algorithm Libraries
Elements are always copied when they are put into a container
An Introduction to STL.
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Presentation transcript:

CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair ) –Don’t require inheritance relationships Types substituted need not have a common base class Need only to be models of the algorithm’s concept Implementations in C++ –Rely on templates, interface-based polymorphism –Algorithms are implemented as function templates –Use types that model iterator concepts –Iterators in turn give access to containers

CSE 332: C++ STL algorithms Example Revisited: Linear Search From Austern: “ Generic Programming and the STL ” Sequential (linear) search: find char c in string s char * strchr (char* s, char c) { while (*s != 0 && *s != c){ ++s; } return *s == c ? s : (char *) 0; } Problem: not very general –“ Range ” of iteration is always defined up to ‘ \0 ’ character –Only works for a “ zero terminated ” string in C/C++

CSE 332: C++ STL algorithms Review in Detail: Linear Search with Ranges First generalization (Austern, pp. 11): use a range char * find1 (char* first, char* last, char c){ while (first != last && *first != c) ++first; return first; } Gives an explicit range (calculate its length – how?) Assumes first is before last (can check – how?) Note how caller checks for success changed: why?

CSE 332: C++ STL algorithms General Requirements for Linear Search Before we try to improve the algorithm further –Let’s come up with a definition of what it needs to do –This helps to plan what to require and what to leave flexible Any linear search implementation must offer a way to: –Indicate the sequence over which search will occur –Represent a position within the sequence –Advance to the next element of the sequence –Detect the end of the sequence –Return a value as an indication of success or failure Goal: meet these requirements flexibly and efficiently

CSE 332: C++ STL algorithms Linear Search over Parameterized Types Second generalization: use templates to parameterize the function argument types template T * find2(T * first, T * last, const T & value){ while (first != last && *first != value) ++first; return first; } How much did the find1 code need to change? One last problem –What if we want to apply this to a data structure whose ranges can’t be traversed via simple pointers?

CSE 332: C++ STL algorithms Linear Search with Generic Iterators Third generalization: separate iterator type parameter The STL’s linear search algorithm (Austern pp. 13): template Iterator find (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) ++first; return first; } Notice how algorithm depends on the iterators Notice how refinements made algorithm more abstract –… but still essentially does the same thing –i.e., algorithm structure (and time complexity) is the same

CSE 332: C++ STL algorithms Algorithm Concepts and Models Remember a concept gives a set of type requirements –Classify/categorize types (e.g., random access iterators) –Tells whether or not a type can or cannot be used with a particular STL algorithm (get a compiler error if it cannot) E.g., we couldn’t use a linked list iterator in find1 or even find2 Any specific type that meets the requirements is a model of that concept –E.g., list ::iterator vs. char * in find Different abstractions (bi-linked list vs. array iterators) No inheritance-based relationship between them But both model iterator concept necessary for find

CSE 332: C++ STL algorithms Concepts and Modeling Review, Continued What very basic concept does the last statement in STL find, (the line return first; ) assume? –Asked another way, what must be able to happen to first when it’s returned from function find ? –Same requirement imposed by by-value iterator parameters What other capabilities are required of the Iterator and T type parameters by the STL find algorithm ? template Iterator find (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) ++first; return first; }

CSE 332: C++ STL algorithms Concepts and Modeling Review, Continued What very basic concept does the last statement in STL find, (the line return first; ) assume? –Asked another way, what must be able to happen to first when it’s returned from function find ? –Same requirement imposed by by-value iterator parameters What other capabilities are required of the Iterator and T type parameters by the STL find algorithm ? template Iterator find (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) ++first; return first; }

CSE 332: C++ STL algorithms Matching an Algorithm to the Iterators it Needs Category/ Operation OutputInputForwardBidirectional Random Access Read =*p (r-value) =*p (r-value) =*p (r-value) =*p (r-value) Access -> [] Write *p= (l-value) *p= (l-value) *p= (l-value) *p= (l-value) Iteration = -= Comparison == != == != = What STL iterator category does find require?

CSE 332: C++ STL algorithms What if an Algorithm Has Alternative Versions? First approach: dynamic dispatch –Different names of implementations –Run-time iterator type test –Calls the best implementation –What are the limitations here? // Based on Austern, pp. 38 template void move_fwd (Iter &i, Distance d) { while (d>0) {--d; ++i} // O(d) } template void move_rand (Iter &i, Distance d) { i+=d; // O(1) } template void move (Iter &i, Distance d) { if (is_rand(i)) move_rand (i, d) else if (is_fwd(i)) move_fwd (i, d) // else... }

CSE 332: C++ STL algorithms Iterator Traits and Category Type Tags Need a few concrete types to use as tags –E.g., empty structs –E.g., input, output, fwd, bidir, and rand Tags provide yet another associated type for iterators –Iterator category –Again, made available by using the traits idiom struct input {}; // empty structs for type tags struct output {}; struct fwd : public input {}; // note inheritance struct bidir : public fwd {}; struct rand : public bidir {}; template struct iterator_traits {... typedef typename I::iterator_category iterator_category; }; template struct iterator_traits {... typedef rand iterator_category; }; template struct iterator_traits {... typedef rand iterator_category; }; (actually, random_access_iterator_tag )

CSE 332: C++ STL algorithms Algorithm Dispatching via Category Tags Static dispatching –Implementations provide different signatures –Iterator type is evaluated at compile-time –Links to the best implementation Notice how type tags are used // Based on Austern, pp. 38, 39 template void move (Iter i, Distance d, fwd) { while (d>0) {--d; ++i;} // O(d) } template void move (Iter i, Distance d, rand) { i += d; // O(1) } template void move (Iter i, Distance d) { move (i, d, iterator_traits :: iterator_category() ) } concrete tag (empty struct) type explicit constructor call concrete tag (empty struct) type

CSE 332: C++ STL algorithms Organization of Algorithms within the STL The header file contains –Non-modifying sequence operations Do some calculation but don’t change sequence itself Examples include count, count_if –Mutating sequence operations Modify the order or values of the sequence elements Examples include copy, random_shuffle –Sorting and related operations Modify the order in which elements appear in a sequence Examples include sort, next_permutation The header file contains –General numeric operations Scalar and matrix algebra, especially used with vector Examples include accumulate, inner_product

CSE 332: C++ STL algorithms Example of Using Non-Modifying Algorithms count algorithm –Moves through iterator range –Checks each position for equality –Increases count if equal #include using namespace std; int main (int, char * []) { vector v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(2); int i = 7; cout << i << " appears " << count(v.begin(), v.end(), i) << " times in v" << endl; i = 2; cout << i << " appears " << count(v.begin(), v.end(), i) << " times in v" << endl; return 0; } /* output is 7 appears 0 times in v 2 appears 2 times in v */

CSE 332: C++ STL algorithms Using a Function Object to Extend an Algorithm count_if algorithm –Generalizes the count algorithm –Instead of comparing for equality to a value –Applies a given predicate function object (functor) –If functor’s result is true, increases count #include using namespace std; template struct odd { bool operator() (T t) const { return (t % 2) != 0; } }; int main (int, char * []) { vector v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(2); cout << "there are " << count_if(v.begin(), v.end(), odd ()) << " odd numbers in v" << endl; return 0; } /* output is there are 2 odd numbers in v */

CSE 332: C++ STL algorithms Example of Using Mutating Algorithms copy algorithm –Copies from an input iterator range into an output iterator –Note use of default constructor to get an “off-the-end” (here, “end-of-file”) input iterator –Note use of noskipws (need to make sure container behavior matches what you want to do) ifstream input_file (input_file_name.c_str()); ofstream output_file (output_file_name.c_str()); input_file >> noskipws; istream_iterator i (input_file); ostream_iterator o (output_file); copy (i, istream_iterator (), o); cout << "copied input file: " << input_file_name << endl << " to output file: " << output_file_name << endl; return 0; } /* output: Makefile Makefile2 copied input file: Makefile to output file: Makefile2 diff Makefile Makefile2 */ #include using namespace std; int main (int argc, char * argv[]) { if (argc != 3) {return 1;} string input_file_name (argv[1]); string output_file_name (argv[2]);

CSE 332: C++ STL algorithms Example of Using Sorting Algorithms sort algorithm –Reorders a given range –Can also plug in a functor to change the ordering function next_permutation algorithm –Generates a specific kind of reordering, called a “permutation” –Can use to generate all possible orders of a given sequence #include using namespace std; int main (int, char * []) { string s = "asdf"; cout << "original: " << s << endl; sort (s.begin(), s.end()); cout << "sorted: " << s << endl; string t (s); cout << "permutations:" << endl; do { next_permutation (s.begin(), s.end()); cout << s << " "; } while (s != t); cout << endl; return 0; } /* output is original: asdf sorted: adfs permutations: adsf afds afsd asdf asfd dafs dasf dfas dfsa dsaf dsfa fads fasd fdas fdsa fsad fsda sadf safd sdaf sdfa sfad sfda adfs */

CSE 332: C++ STL algorithms Example of Using Numeric Algorithms accumulate algorithm –Sums up elements in a range (based on a starting sum value) inner_product algorithm –Computes the inner (also known as “dot”) product of two matrixes: sum of the products of their respective elements #include using namespace std; int main (int, char * []) { vector v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(2); cout << "v contains "; for (size_t s = 0; s < v.size(); ++s) { cout << v[s] << " "; } cout << endl; cout << "the sum of the elements in v is " << accumulate (v.begin(), v.end(), 0) << endl; cout << "the inner product of v and itself is " << inner_product (v.begin(), v.end(), v.begin(), 0) << endl; return 0; } /* output is: v contains the sum of the elements in v is 8 the inner product of v and itself is 18 */

CSE 332: C++ STL algorithms Concluding Remarks STL algorithms give you useful, generic functions –Combine easily with a variety of containers/iterators –Support many common data structure manipulations Finding and modifying values, re-ordering, numeric operations –Reusing them saves you from writing code Many STL algorithms can be extended –Especially by plugging functors into them –We’ve looked at how to use a few functors –Next lecture we’ll look at how functors work You can also create your own generic algorithms –If something you need is not in the STL –Think about the iterator and data type concept it requires –Implement a version that works as generically as possible –Use traits-based dispatching to support more specific (and thus more efficient) versions