Generic Programming and the STL Andreas Fabri GeometryFactory.

Slides:



Advertisements
Similar presentations
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
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.
Standard Containers: Vectors
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
More on the STL vector list stack queue priority_queue.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
1 STL Overview Prof. Brinton Gordon College. 2 Standard Template Library (STL) Part of ISO-OSI Standard C++ Library 1998 Object oriented programming is.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
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.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
Writing Your Own STL Container Ray Lischner
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
 2003 Prentice Hall, Inc. All rights reserved stack Adapter stack –Header –Insertions and deletions at one end –Last-in, first-out (LIFO) data.
Data Structures Using C++ 2E
Containers Overview and Class Vector
Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
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.
C++ STL CSCI 3110.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
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.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
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.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
Lecture 7 : Intro. to STL (Standard Template Library)
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.
A gentle introduction to the standard template library (STL) Some references:
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.
The Standard Template Library Container Classes Version 1.0.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
C++ Review STL CONTAINERS.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
CS212: Object Oriented Analysis and Design Lecture 26: STL Containers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 - Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
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.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Standard Template Library (STL)
Chapter 22: Standard Template Library (STL)
Iterators and STL Containers
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Standard Template Library
Standard Template Library
Presentation transcript:

Generic Programming and the STL Andreas Fabri GeometryFactory

GeometryFactoryGeneric Programming and the STL2 int min(int a, int b) float min(float a, float b) template Comparable min(Comparable a, Comparable b) { return (a<b) ? a : b; } BigInt n(9), m(8), r; r = min( n, m ); BigInt is a model for the concept Comparable 0.1 Function Templates

GeometryFactoryGeneric Programming and the STL3 0.2 Class Templates template class list { void push_back(const T& x); typedef... iterator; iterator begin(); iterator end(); }; list ints; list vertex_handles;

GeometryFactoryGeneric Programming and the STL4 1 Standard Template Library (STL) Part of ISO-OSI Standard C++ Library 1998 Object oriented programming is about reuse –STL has many reusable components –Divided into containers iterators algorithms

GeometryFactoryGeneric Programming and the STL5 1.1Introduction to Containers Three types of containers –sequence containers –associative containers –container adapters Near-containers - similar to containers, without all the capabilities –C-like arrays –string –bitset for maintaining sets of 1 / 0 flag values –valarray - high-speed mathematical vector operations The containers have similar functions

GeometryFactoryGeneric Programming and the STL6 1.1Introduction to Containers (II) vector direct access to any element deque rapid insertion at front or back direct access to any element list rapid insertion and deletion anywhere set rapid lookup, no duplicates multiset rapid lookup, duplicates map, multimap store key/value pairs stack last-in-first-out queue first-in-first-out priority_queue highest priority element is first

GeometryFactoryGeneric Programming and the STL7 1.1Introduction to Containers (III) Common member functions of all STL containers –constructors, destructors –assignment, all comparison operators –swap –empty –max_size –size Use if(c.empty()) not if(c.size() == 0)

GeometryFactoryGeneric Programming and the STL8 1.2Introduction to Iterators Iterators are similar to pointers –point to element in a container –iterator operators uniform for all containers * dereferences, ++ advances pointer container.begin() returns iterator pointing to first element container.end() returns iterator pointing after last element for(it = c.begin(); it != c.end(); it++) {... } it

GeometryFactoryGeneric Programming and the STL9 1.2Iterator Categories All iterators: p++, ++p Input iterators: v = *p, p1 = p2, p1 == p2, p1 != p2 Output iterators: *p = v, p1 = p2 Forward iterators: all above Bidirectional iterators: p--, --p Random access iterators: p+=i; p-=i, p+i, p-i,,…

GeometryFactoryGeneric Programming and the STL10 1.2Constness of Iterators Examples vector ::iterator it = v.begin(); vector ::const_iterator cit = v.begin(); *cit = 24; // does not compile *it = 24; // ok void fct(const vector & v) { vector ::iterator it; it = v.begin(); // does not compile }

GeometryFactoryGeneric Programming and the STL11 1.2Iterator Adapters Everything that behaves like an iterator is an iterator –Insert iterator –Stream iterator –Reverse iterators Example: list L; copy(istream_iterator (cin), istream_iterator ::reverse_iterator r1 = L.rbegin(), r2 = L.rend();

GeometryFactoryGeneric Programming and the STL12 1.2CGAL Circulators Geometric structures are often circular Leads to other loop: Circ c1 = vertex.incident_vertices(); Circ done = c1; do { something(*c1); c1++; } while(c1 != done);

GeometryFactoryGeneric Programming and the STL13 1.3Introduction to Algorithms STL provides algorithms used generically across containers –operate on elements indirectly through iterators –often operate on sequences of elements defined by pairs of iterators –algorithms often return iterators, such as find() –premade algorithms save programmers time and effort

GeometryFactoryGeneric Programming and the STL14 2Sequence Containers Three sequence containers –vector - based on arrays –deque - based on arrays –list - robust linked list

GeometryFactoryGeneric Programming and the STL vector Sequence Container vector –#include –data structure with contiguous memory locations –use the subscript operator [] –used when data must be sorted and easily accessible –when memory exhausted allocates a larger, contiguous area of memory copies itself there deallocates the old memory –has a random access iterator

GeometryFactoryGeneric Programming and the STL vector Sequence Container Declarations –vector v; –vector v(7812); –template vector v(It begin, It end); –type - int, float, Point, whatsoever –Warning: Beware of vector Iterators: –vector ::const_iterator it; vector ::iterator it = v.begin(); *(it1 + 5) = 34;

GeometryFactoryGeneric Programming and the STL vector Sequence Container (II) vector functions, for vector object v v.push_back(value) - add element to end v.size() - current size of vector v.capacity() - how much vector can hold before reallocation v.reserve(n) - allow vector to avoid reallocation v.insert( pointer, value ) - inserts value before pointer. template v.insert( pointer, It begin, It end ).

GeometryFactoryGeneric Programming and the STL vector Sequence Container (III) vector functions and operations v.erase( pointer ) remove element from container v.erase( pointer1, pointer2 ) remove elements starting from pointer1 and up to (not including) pointer2. v.clear() erases entire container. v[elementNumber] = value; assign value to an element v.at[elementNumber] = value; as above, with range checking throws out_of_bounds exception

GeometryFactoryGeneric Programming and the STL list Sequence Container list container –#include –efficient insertion/deletion anywhere in container –doubly-linked list –bidirectional iterators There exists also a non-standard slist –singly-linked list –forward iterator

GeometryFactoryGeneric Programming and the STL list Sequence Container (II) list functions for listObject and otherObject listObject.sort() sorts in ascending order listObject.splice(iterator, otherObject); inserts values from otherObject before location of iterator listObject.merge(otherObject) removes otherObject and inserts it into listObject, sorted listObject.unique() removes duplicate elements listObject.swap(otherObject); exchange contents listObject.assign(iterator1, iterator2) replaces contents with elements in range of iterators listObject.remove(value) erases all instances of value

GeometryFactoryGeneric Programming and the STL deque Sequence Container deque ("deek") - double-ended queue –#include –indexed access using [] –efficient insertion/deletion in front and back –non-contiguous memory: "smarter" pointers same basic operations as vector –adds push_front / pop_front - insertion/deletion at beginning of deque

GeometryFactoryGeneric Programming and the STL22 3Associative Containers Associative containers –provide direct access to store and retrieve elements via keys (search keys) 4 types: multiset, set, multimap and map –keys in sorted order –multiset and multimap allow duplicate keys –multimap and map allow keys and associate values

GeometryFactoryGeneric Programming and the STL23 Excursion: Function Objects template struct less { bool operator()(const T& lhs, const T& rhs) const { return lhs < rhs; } }; less is_smaller; if(is_smaller(45, 34)){..}

GeometryFactoryGeneric Programming and the STL multiset Associative Container multiset - fast storage, retrieval of keys –allows duplicates Ordering by comparator function object less - sorts keys in ascending order multiset > integers; CGAL comparator function objects typedef CGAL::Cartesian K; multiset points;

GeometryFactoryGeneric Programming and the STL multiset Associative Container (II) Functions for multiset object msObject –msObject.insert(value) - inserts value –msObject.find(value) - returns iterator to first instance of value, or msObject.end() –msObject.lower_bound(value)- returns iterator to first location of value –msObject.upper_bound(value)- returns iterator to location after last occurrence of value –for a pair object p p = msObject.equal_range(value) sets first and second to lower_bound and upper_bound for a given value

GeometryFactoryGeneric Programming and the STL set Associative Container set –implementation identical to multiset –unique keys - duplicates ignored and not inserted –supports bidirectional iterators (but not random access) –#include

GeometryFactoryGeneric Programming and the STL map Associative Container map –fast storage/retrieval of unique key/value pairs –#include –one-to-one mapping (duplicates ignored) –use [] to access values for map M; M[30] = ; sets the value of key 30 to –if subscript not in map, creates new key/value pair –Efficiency remark: Use insert to insert, operator[] to update

GeometryFactoryGeneric Programming and the STL Non Standard Associative Container hash_(multi)set, hash_(multi)map –Not part of the standard, but provided by some STLs –REALLY fast storage/retrieval of unique key/value pairs –Based on hashing and not on binary trees –No order, but provide iterators CGAL::Unique_hash_map –Does not provide removal, only insertion –No order, no iterators –Designed for speed, and minimal memory consumption

GeometryFactoryGeneric Programming and the STL29 4Container Adapters container adapters: stack, queue, priority_queue –not first class containers –do not support iterators –do not provide actual data structure –programmer can select implementation of the container adapters –have member functions push() and pop()

GeometryFactoryGeneric Programming and the STL stack Adapter stack –insertions and deletions at one end –last-in-first-out data structure –implemented with vector, list, and deque (default) –#include Declarations stack > myStack; stack > myOtherStack; stack anotherStack;

GeometryFactoryGeneric Programming and the STL queue Adapter queue - insertions at back, deletions at front –first-in-first-out data structure –implemented with list or deque –#include Functions –push(element) - (push_back) add to end –pop(element) - (pop_front) remove from front –empty() - test for emptiness –size() - returns number of elements Example: queue values; //create queue values.push(1.2); // values: 1.2 values.push(3.4); // values: values.pop(); // values: 1.2

GeometryFactoryGeneric Programming and the STL priority_queue Adapter insertions in sorted order, deletions from front –implemented with vector or deque –highest priority element always removed first heapsort puts largest elements at front less by default, programmer can specify another Functions –push - (push_back then reorder elements ) –pop - (pop_back to remove highest priority element ) –size –empty

GeometryFactoryGeneric Programming and the STL33 5Algorithms Before STL –class libraries were incompatible among vendors –algorithms built into container classes STL separates containers and algorithms –easier to add new algorithms –more efficient, avoids virtual function calls

GeometryFactoryGeneric Programming and the STL34 Excursion: Function Object Adapters template struct less : public binary_function { bool operator()(const T& lhs, const T& rhs) const { return lhs < rhs; } }; list L(..); less ::iterator it = find_if(L.begin(), L.end(), not1(bind2nd(less (),34)));

GeometryFactoryGeneric Programming and the STL for_each, accumulate, transform for_each(iterator1, iterator2, function); list L(..); int sum = accumulate(L.begin(), L.end(), 0, plus ()); transform(istream_iterator (cin), istream_iterator (), ostream_iterator (cout), mem_fun_ref(Point::x));

GeometryFactoryGeneric Programming and the STL36 5.2Basic Searching Algorithms find(iterator1, iterator2, value) –returns iterator pointing to first instance of value find_if(iterator1, iterator2, function) –like find, but returns an iterator when function returns true. binary_search(iterator1, iterator2, value) –searches an ascending sorted list for value using a binary search

GeometryFactoryGeneric Programming and the STL37 5.3Sorting Algorithms sort(begin, end) partial_sort(begin, begin+N, end) –finds first N and sorts them nth_element(begin, begin+N, end) –finds first N, not sorted partition(begin, end, function) –splits in two intervals stable_sort, stable_partition Remarks –All take optionaly a comparison function –std::sort is faster than clib sort

GeometryFactoryGeneric Programming and the STL equal, mismatch, lexicographical_compare Functions to compare sequences of values equal –returns true if sequences are equal (uses == ) –returns false if of unequal length equal(iterator1, iterator2, iterator3); –compares sequence from iterator1 up to iterator2 with the sequence beginning at iterator3 –Containers can be of different types

GeometryFactoryGeneric Programming and the STL fill, fill_n, generate, generate_n STL functions, change containers. fill - changes a range of elements (from iterator1 to iterator2 ) to value – fill(iterator1, iterator2, value); fill_n - changes specified number of elements, starting at iterator1 –fill_n(iterator1, quantity, value); generate - like fill, but calls a function for value –generate(iterator1, iterator2, function); generate_n - like fill_n, but calls function for value –generate(iterator1, quantity, value)

GeometryFactoryGeneric Programming and the STL swap, iter_swap and swap_ranges swap(element1, element2) - exchanges two values swap( a[ 0 ], a[ 1 ] ); iter_swap(iterator1, iterator2) - exchanges the values to which the iterators refer swap_ranges(iterator1, iterator2, iterator3) - swap the elements from iterator1 to iterator2 with the elements beginning at iterator3

GeometryFactoryGeneric Programming and the STL copy_backward, merge, unique, reverse copy_backward(iterator1, iterator2, iterator3) –copy the range of elements from iterator1 to iterator2 into iterator3, but in reverse order. merge(iter1, iter2, iter3, iter4, iter5) –ranges iter1-iter2 and iter3-iter4 must be sorted in ascending order. – merge copies both lists into iter5, in ascending order. unique(iter1, iter2) - removes duplicate elements from a sorted list, returns iterator to new end of sequence. reverse(iter1, iter2)- reverses elements in the range of iter1 to iter2.

GeometryFactoryGeneric Programming and the STL42 5.8Remove does (not) Remove Member function: L.remove(Point(0,0)); Algorithm moves at end: list L(istream_iterator (cin), istream_iterator ()); list ::iterator eit; eit = remove(L.begin(), L.end(), Point(0,0)); L.erase(eit, L.end());

GeometryFactoryGeneric Programming and the STL43 6 Other Features of the STL Streams strings, wide strings locales (for internationalization) numerical valarray

GeometryFactoryGeneric Programming and the STL44 7 References N.M. Josuttis, The C++ Standard Library, Addison- Wesley 2001 S.Meyers, Effective STL, Addison-Wesley