The C++ Algorithm Libraries

Slides:



Advertisements
Similar presentations
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Advertisements

STL. What is STL? Standard Templates Library Templates are best used for –Defining containers for storing data –Some kinds of algorithms that work the.
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
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: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair )
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
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.
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.
File I/O ifstreams and ofstreams Sections 11.1 &
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 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.
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”
Overview of C++ Templates
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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++ 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)
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Lecture 36 OOP The STL Standard Template Library
Motivation for Generic Programming in C++
Examples (D. Schmidt et al)
CS212: Object Oriented Analysis and Design
Chapter 12 Classes and Abstraction
Introduction to Generic Programming in C++
Concepts of Programming Languages
Chapter 6 CS 3370 – C++ Functions.
5.13 Recursion Recursive functions Functions that call themselves
Generic Algorithms (TIC++V2:C6)
Motivation and Overview
Command Line Arguments
CS3340 – OOP and C++ L. Grewe.
Working with Strings Lecture 2 Hartmut Kaiser
Generic Programming Techniques in C++
Starting Out with C++ Early Objects Eighth Edition
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
C++ Templates L03 - Iterator 10 – Iterator.
10 – Iterators C++ Templates 4.6 The Iterator pgs
ADT Implementations: Templates and Standard Containers
C++ Functions, Classes, and Templates
Lab 03 - Iterator.
Introduction to the Standard Template Library
C++ File Structure and Intro to the STL
Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes.
STL: Traversing a Vector
C++ Templates L03 - Iterator 10 – Iterator.
Lecture 8-2 : STL Iterators and Algorithms
C++ Templates L03 - Iterator 10 – Iterator.
CMSC 341 C++ and OOP.
Standard Template Library
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
CMSC 341 C++ and OOP.
An Introduction to STL.
SPL – PS1 Introduction to C++.
Standard Template Library
Presentation transcript:

The C++ Algorithm Libraries A standard collection of generic algorithms Applicable to various types and containers E.g., sorting integers (int) vs. intervals (pair<int, int>) E.g., sorting elements in a vector vs. in a C-style array Polymorphic even without inheritance relationships Types substituted need not have a common base class Must only provide the operators the algorithm needs Significantly used with the sequence containers To reorder elements within a container’s sequence To store/fetch values into/from a container To calculate various values and properties from it

Motivating Example: Searching a String 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++ What make strchr not very general? 1. You can only search for a specific type 2. The data structure you can search in is limited to the null-terminated array

Improving Linear Search with Ranges First generalization (Austern, pp. 11): use a range (something that sequential containers can give us!) 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? What make strchr not very general? 1. You can only search for a specific type 2. The data structure you can search in is limited to the null-terminated array

Linear Search over Parameterized Types Second generalization: use templates to parameterize the function argument types template <typename T> 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 container (e.g., list) whose range can’t be traversed via simple pointers?

Linear Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm (Austern pp. 13): template <typename Iterator, typename T> 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

Organization of C++ Algorithm Libraries The <algorithm> 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 <numeric> header file contains General numeric operations Scalar and matrix algebra, especially used with vector<T> Examples include accumulate, inner_product

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

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<char> i (input_file); ostream_iterator<char> o (output_file); copy (i, istream_iterator<char>(), o); cout << "copied input file: " << input_file_name << endl << " to output file: " << output_file_name << endl; return 0; } /* output: cdgill@hive> ./copytest Makefile Makefile2 copied input file: Makefile to output file: Makefile2 cdgill@hive> diff Makefile Makefile2 cdgill@hive> */ #include <iostream> #include <string> #include <fstream> #include <iterator> #include <algorithm> 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]);

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 <iostream> #include <string> #include <algorithm> 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 */

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 <iostream> #include <vector> #include <numeric> using namespace std; int main (int, char * []) { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); 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 1 2 3 2 the sum of the elements in v is 8 the inner product of v and itself is 18 */

Concluding Remarks C++ libraries give you useful, generic algorithms 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 further Especially by plugging callable entities into them Next time we’ll look at how callables work, and how to use them, as well as at algorithms and iterators in more detail