Generic Programming in the STL and Beyond David R. Musser Rensselaer Polytechnic Institute.

Slides:



Advertisements
Similar presentations
M The University Of Michigan Andrew M. Morgan EECS Lecture 22 Savitch Ch. 16 Intro To Standard Template Library STL Container Classes STL Iterators.
Advertisements

Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Generic Programming and Formal Methods David R. Musser Rensselaer Polytechnic Institute.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
What is generic programming? The essence of the generic programming approach is concept development: systematic classification of computing components.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Concept= a set of abstractions (e.g., types) (Generic Programming) Programming with Concepts defined by a set of requirements {vector, deque, list, set,
Quick Overview of STL STL = Standard Template Library Main concept : Container, Iterator Application : Linked list, Stack etc.
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.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Generic programming starts with algorithms. Lift Minimal requirements: works with maximal family of types Concrete algorithm: requires specific data type.
1 Priority Queues CPS212 Gordon College VIP. 2 Introduction to STL Priority Queues Adaptor container - underlying container may be either: – a template.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
1 Concepts: Linguistic Support for Generic Programming in C++ Douglas Gregor Jeremy Siek Gabriel Dos Reis Jaakko Järvi Bjarne Stroustrup Andrew Lumsdaine.
Data Structures Using C++ 2E
Containers Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
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.
Review for Final Andy Wang Data Structures, Algorithms, and Generic Programming.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
1 Iterators Good reference site:
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
CS 403: Programming Languages Lecture 24 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Intro to the C++ STL Timmie Smith September 6, 2001.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
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)
Programming in C++ Michal Brabec Petr Malý. Standard Template Library Containers - vector, map, set, deque, list Algorithms - copy, replace, sort, find.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
Chapter 8 Writing Generic Functions. Objectives Understand the use of generic functions. Learn about the use of templates, their advantages and pitfalls.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Lecture 7-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Introduction to Templates and Standard Template Library 1.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
CS212: Object Oriented Analysis and Design
Programming with ANSI C ++
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Programming with Concepts
Chapter 22: Standard Template Library (STL)
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
CS212: Object Oriented Analysis and Design
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
Containers, Iterators, Algorithms, Thrust
Standard Template Library
Standard Template Library
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

Generic Programming in the STL and Beyond David R. Musser Rensselaer Polytechnic Institute

Generic programming starts with algorithms

Lift Minimal requirements: works with maximal family of types Concrete algorithm: requires specific data type Less specialized: works with more than one type A 0 A 1 Lift A m Remove an unneeded requirement on the type Generic algorithm... Start here

Maximal with respect to what?

Lift Maintain usefulness of the algorithm – make efficiency part of the requirements Concrete algorithm A 0 A 1 Lift A m Generic algorithm...

float max_element(float a[], int N) { if (N == 0) throw MaxElementEmptyArrayError; int first = 0; float max = a[0]; while (++first < N) if (max < a[first]) max = a[first]; return max; }

int max_element(float a[], int first, int last) { if (first == last) return first; int result = first; while (++first != last) if (a[result] < a[first]) result = first; return result; }

float_list_node* max_element(float_list_node* first, float_list_node* last) { if (first == last) return first; float_list_node* result = first; while (first->next != last) if (result->data data) result = first; return result; }

int max_element(float a[], int first, int last) { if (first == last) return first; int result = first; while (++first != last) if (a[result] < a[first]) result = first; return result; }

template int max_element(E a[], int first, int last) { if (first == last) return first; int result = first; while (++first != last) if (a[result] < a[first]) result = first; return result; }

template T* max_element(T* first, T* last) { if (first == last) return first; T* result = first; while (++first != last) if (*result < *first) result = first; return result; }

template ForwardIterator max_element(ForwardIterator first, ForwardIterator last) { if (first == last) return first; ForwardIterator result = first; while (++first != last) if (*result < *first) result = first; return result; }

int a[] = {6, 3, 7, 5}; int* ai = max_element(a, a+4); vector v(a, a+4); vector ::iterator vi = max_element(v.begin(), v.end()); list x(a, a+4); list ::iterator li = max_element(x.begin(), x.end());...

Forward Container Concept max_element Generic algorithm on jk jk k = ++j *j = 3 *k = 7 ++i *i i==j

What is a concept?

Concept IntensionExtension Requirement 1 Requirement 2. Requirement N Abstraction 1 Abstraction 2. Abstraction K.

Polygon Concept IntensionExtension Closed plane figure N sides...

Container Concept IntensionExtension Must be a type whose objects can store other objects (elements) Must have an associated iterator type that can be used to iterate through the elements.... vector, for any T deque for any T list for any T slist for any T set for any T map for any T self_adjusting_bag

A Algorithm A works with every type T in concept C Definition: an algorithm is generic if it works with every type in a concept “works”: is correct and efficient C T … …

What does it mean to refine a concept?

Requirement 1 Requirement 2... Requirement N refine Requirement 1 Requirement 2... Requirement N Requirement N+1 Abstraction 1 Abstraction 2... Abstraction K... Abstraction 1 Abstraction 3... Abstraction 2... Abstraction K... More Requirements, Fewer Abstractions

Polygon Concept Closed plane figure N sides refine Closed plane figure N sides N = 3 Triangle Concept...

Requirement 1 Requirement 2... Requirement N refine Requirement 1 Requirement 2... Requirement N Requirement N+1 Abstraction 1 Abstraction 2... Abstraction K... Abstraction 1 Abstraction 3... Abstractions that remain are ones that are more specialized.

Polygon Concept Closed plane figure N sides refine Closed plane figure N sides Equal side lengths Equilateral Polygon Concept...

Container Concept refine Forward Container Concept Reversible Container Concept Random Access Container Concept

Forward Container Concept IntensionExtension Container Intension Elements must be arranged in a definite order Iterator type must model Forward Iterator concept... vector for any T deque for any T list for any T slist for any T set for any T map for any T self_adjusting_bag

Reversible Container Concept IntensionExtension Forward Container Intension Must have an associated reverse iterator type Iterator and reverse iterator types must model Bidirectional Iterator concept... vector for any T deque for any T list for any T set for any T map for any T slist for any T

Random Access Container Concept IntensionExtension Reversible Container Intension Iterator types must model Random Access Iterator concept... vector for any T deque for any T list for any T set for any T map for any T

A more refined concept permits better algorithms

refine A Algorithm B can be more efficient than A (B doesn’t have to work with as many types as A) B C D

For any Polygon P Circumference(P) = sum = 0; for s in sides(P) sum += length(s) For any Equilateral Polygon P Circumference(P) = N * side_length(P)

Container refine Forward Container Reversible Container Random Access Container enables generic algorithms copy, equal, transform, … enables find, merge, fill, replace, remove, unique, rotate, max_element, … enables reverse, partition, rotate, inplace_merge, … enables sort, binary_search, rotate random_shuffle, … Requires Input Iterators Forward Iterators Bidirectional Iterators Random Access Iterators

Container refine Forward Container Reversible Container Random Access Container enables generic algorithms copy, equal, transform, … enables find, merge, fill, replace, remove, unique, rotate, max_element, … enables reverse, partition, rotate, inplace_merge, … enables sort, binary_search, rotate, random_shuffle, … Requires Input Iterators Forward Iterators Bidirectional Iterators Random Access Iterators

Container Forward Container Reversible Container Random Access Container Sequence Front Insertion Sequence Back Insertion Sequence Vector Deque Slist List …

Concept C IntensionExtension A models C  A is in Extension of C A  A satisfies Intension of C (A makes R, …, R true) R, …, R N1 1N...

Output Iterator Forward Iterator Bidirectional Iterator Random Access Iterator Vector iterator Input Iterator Deque iterator Slist iterator List iterator Istream iterator Ostream iterator

template ForwardIterator max_element(ForwardIterator first, ForwardIterator last) { if (first == last) return first; ForwardIterator result = first; while (++first != last) if (*result < *first) result = first; return result; }

template Iterator max_element(Iterator first, Iterator last) { if (first == last) return first; Iterator result = first; while (++first != last) if (*result < *first) result = first; return result; }

int a[] = {6, 3, 7, 5}; int* ai = max_element(a, a+4); vector v(a, a+4); vector ::iterator vi = max_element(v.begin(), v.end()); list x(a, a+4); list ::iterator li = max_element(x.begin(), x.end());

int a[] = {6, 3, 7, 5}; assert int* models Forward Iterator; int* ai = max_element(a, a+4); vector v(a, a+4); assert vector ::iterator models Forward Iterator; vector ::iterator vi = max_element(v.begin(), v.end()); list x(a, a+4); assert list ::iterator models Forward Iterator; list ::iterator li = max_element(x.begin(), x.end());

template Assume that T satisfies Intension of C when checking uses of T in the algorithm. We need to use both the syntactic and the semantic properties listed in the intension. assert T models C; Check that T satisfies Intension of C. Should check that both the syntactic and the semantic requirements are satisfied.

What’s this about semantic requirements?

template ForwardIterator max_element(ForwardIterator first, ForwardIterator last) { if (first == last) return first; ForwardIterator result = first; while (++first != last) if (*result < *first) result = first; return result; }

template ForwardIterator max_element(ForwardIterator first, ForwardIterator last, StrictWeakOrder compare){ if (first == last) return first; ForwardIterator result = first; while (++first != last) if (compare(*result,*first)) result = first; return result; }

Strict Weak Order: assumed in all STL sorting-related algorithms

<:T  T  bool Transitive[E/<] E(x,y)  not(x<y) & not(y<x) Binary Relation for all x: not(x < x) Irreflexive for all x, y, z: x < y & y < z implies x < z Transitive Strict Partial Order Strict Weak Order Functor

Irreflexive Transitive Transitive[E/<] E(x,y)  not(x<y) & not(y<x) Strict Weak Order for all x, y: x < y | y < x | x = y Trichotomy Total Order Sufficient for all STL sorting-related generic algorithms Not needed!

vector v; // Put some elements in v: // Sort v into descending order: sort(v.begin(), v.end(), greater_equal ()); // Why doesn’t the above call // terminate?

vector v; // Put some elements in v: // Sort v into descending order: sort(v.begin(), v.end(), greater ()); // Now we get here - that’s better!

vector v; // Put some elements in v:... // Sort v into descending order: assert greater models Strict Weak Order; sort(v.begin(), v.end(), greater ());

ContainerIteratorAlgorithmFunctorAdaptorAllocator STL Concepts

ContainerIteratorAlgorithmFunctorAdaptorAllocator Boost Graph Library Concepts Graph Visitor BFS Visitor DFS Visitor Uniform Cost Visitor See

Graph Algorithm Graph Algorithm + Visitor = More Specialized Algorithm Visitor BFS Visitor DFS Visitor Uniform Cost Visitor Algorithm DFS + topological_sort_visitor = Topological Sort + cycle_detection_visitor = Cycle Detector

Let’s summarize

Lift Concrete algorithms A 0 A 1 Lift A m Generic algorithms. Concept Taxonomy Useful Data and Algorithm Abstractions – a Generic Library C requires... template <typename T models C>... assert T models C Making Concepts First Class Constructs... for formal checking of syntactic and semantic properties and using them in software engineering Algorithms, Concepts & Challenges