1 STL Containers Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in a class at Florida International University may copy or print.

Slides:



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

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
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.
. 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.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
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.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
Writing Your Own STL Container Ray Lischner
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
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.
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)
C++ STL CSCI 3110.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
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:
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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.
Chapter 22 STL Containers §22.1 STL Basics §22.2 STL Iterators §22.3 Sequence Containers §22.4 Associative Containers §22.5 Container Adapters.
 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.
A gentle introduction to the standard template library (STL) Some references:
Intro to the C++ STL Timmie Smith September 6, 2001.
The Standard Template Library Container Classes Version 1.0.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using.
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
Vectors Holds a set of elements, like an array
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Iterators and STL Containers
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:

1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print the contents of this slide show. Last update: 3/30/2003

Copyright 2003, Kip R.Irvine2 Standard Template Library (STL) Created by Alexander Stepanov and Meng Lee at Hewlett-Packard Key components: containers, iterators, algorithms Helps you avoid having to re-invent standard container implementation code Design choice: generic classes chosen for runtime efficiency more efficient than object-based containers that use polymorphism

Copyright 2003, Kip R.Irvine3 Standard Template Library (STL) Recently incorporated into the Standard C++ Library STL Programmers' Guide available at: Latest release: 3.3, June 2000.

Copyright 2003, Kip R.Irvine4 Types of Containers Sequence containers vector deque list Associative containers set, multiset map, multimap Container adapters stack queue priority_queue

Copyright 2003, Kip R.Irvine5 Required Headers Class name same as header:,,,, Also: queue, priority_queue set, multiset map, multimap

Copyright 2003, Kip R.Irvine6 Error Handling Exceptions are never thrown by STL classes In fact, exceptions and templates don't mix Very little error checking exists in STL classes

Copyright 2003, Kip R.Irvine7 Common Typedefs value_type type of element stored in the container reference, const_reference reference to type of element stored in the container pointer pointer to the type of element stored in the container iterator, const_iterator a forward iterator that points to the type of element stored in the container reverse_iterator, const_reverse_iterator a reverse iterator that points to the type of element stored in the container

Copyright 2003, Kip R.Irvine8 Common typedefs in STL (cont) difference_type type of the result of subtracting two iterators size_type type used to count items in a container, and index through a sequence container

Copyright 2003, Kip R.Irvine9 Common Member Functions default constructor, copy constructor, destructor empty max_size max number of elements for a container size number of elements currently in the container operator = assign one container to another overloaded, >=, ==, != swap

Copyright 2003, Kip R.Irvine10 Common Member Functions beginreturns an iterator (-> first element) endreturns an iterator (-> after last element) eraseerase 1 or more elements clearerase all elements rbeginreturns reverse_iterator rendreturns reverse_iterator

Copyright 2003, Kip R.Irvine11 Element Types for Containers Must have correct copy semantics bitwise default, or overload the assignment ( = ) operator and copy constructor Provide operator < and operator ==

Copyright 2003, Kip R.Irvine12 Types of Iterators Input Iterator (InIt) Used to read an element from a container Moves only in forward direction, one element at a time Cannot pass through a sequence twice Output Iterator (OutIt) Used to write an element to a container Moves only in forward direction, one element at a time Cannot pass through a sequence twice Each iterator's capabilities are a superset of the previously listed iterators.

Copyright 2003, Kip R.Irvine13 Types of Iterators (cont) Forward Iterator (FwdIt) reads and writes in forward direction only retains its position in the container Bidirectional Iterator (BidIt) reads and writes in both directions retains its position in the container Random-Access Iterator (RadIt) reads and writes in randomly accessed positions permits pointer arithmetic Each iterator's capabilities are a superset of the previously listed iterators.

Copyright 2003, Kip R.Irvine14 Iterator Support, by Container stack, queue, priority_queue:no iterators list, set, multiset, map, multimap:bidirectional vector, deque:random

Copyright 2003, Kip R.Irvine15 Invalidating Iterators Some, but not all operations on containers invalidate iterators result: iterator can be stale remember that iterators are basically pointers Examples: list.push_back( ) does not invalidate iterators vector.push_back( ) invalidates all iterators list.erase( ) invalidates only iterators that pointed to the deleted elements check the documentation for each method!

Copyright 2003, Kip R.Irvine16 Sequence Containers

Copyright 2003, Kip R.Irvine17 vector Container sequence container with contiguous memory locations permits direct access to any member via [ ] or at( ) automatically doubles its allocation when current size is exceeded insertion and deletion only permitted at the tail supports random-access iterators all lesser iterators also

Copyright 2003, Kip R.Irvine18 Common vector Functions push_back, pop_back add to end, remove from end size current number of elements capacity storage allocation size begin, end return iterator and const_iterator rbegin, rend return reverse_iterator and const_reverse_iterator front, back return first and last elements

Copyright 2003, Kip R.Irvine19 Common vector Functions at( ) operator [ ] (also found in deque)

Copyright 2003, Kip R.Irvine20 list Sequence Container efficient insertion and deletion at any location deque is more efficient if insertions and deletions are at the ends of the container implemented as doubly-linked list supports bidirectional iterators does not support at( ) or operator [ ]

Copyright 2003, Kip R.Irvine21 list Operations operations not found in vectors: void splice( iterator iter, list & X ) removes values from list X and inserts them into the current list in the position immediately before position iter void push_front( const T & X ) inserts element X at the front of the list void pop_front( ) removes one element from the front of the list void remove( const T& x ) removes all elements found to be equal to X

Copyright 2003, Kip R.Irvine22 Unique list Operations void unique() Removes from the current list every element that is equal to its preceding element void merge( list & other ) Removes from the list other and insert them in sorted order into the current list void reverse() Reverses the order of elements in the current list void sort() Sorts the list in ascending order by automatically calling the < operator function to compare pairs of elements void sort( greater pred ) Sorts the list in descending order by automatically calling the < operator function to compare pairs of elements

Copyright 2003, Kip R.Irvine23 Creating a list list scores; scores.push_back( 20 ); scores.push_front( 10 ); scores.pop_front( ); scores.remove( 20 );// removes "20" cout << "size: " << scores.size( ) << endl; List of lists containing strings: list > L; Disable Microsoft VS 6.0 warning message that appears when templates contain strings: #ifdef _DEBUG #pragma warning( disable : 4786 ) #endif

Copyright 2003, Kip R.Irvine24 Printing a list template void print( const list & aList ) { if ( aList.empty() ) cout << "List is empty"; else { list ::const_iterator I = aList.begin( ); for( ; I != aList.end( ); I++ ) cout << *I << ", "; cout << endl; }

Copyright 2003, Kip R.Irvine25 Removing list Duplicates list scores; scores.push_back( 10 ); scores.push_back( 20 ); scores.push_back( 30 ); scores.unique( ); print( scores );// 10, 20, 30

Copyright 2003, Kip R.Irvine26 List of Lists typedef list stringList; stringList s; s.push_back( "Dan" ); s.push_back( "Bill" ); s.push_back( "Anne" ); // a list containing lists of strings list L; L.push_back( s );

Copyright 2003, Kip R.Irvine27 Associative Containers

Copyright 2003, Kip R.Irvine28 Associative Containers keys are always kept in sorted order iterator always traverses in sort order set – single key values equivalent to Java's TreeSet multiset – duplicate keys allowed map – contains pairs (key, value) key is unique equivalent to Java's TreeMap multimap key need not be unique

Copyright 2003, Kip R.Irvine29 Sets: Three Ways to Insert Items insert single value, returning an iterator iterator insert( const value_type & x); start searching for insert point after iterator it: iterator insert( iterator it, const value_type & x ); insert sequence of elements in the range [first, last): void insert( const value_type * first, const value_type * last );

Copyright 2003, Kip R.Irvine30 Examples: Inserting and Finding Create a multiset and insert single values: multiset B; B.insert( 30 ); B.insert( 20 ); Insert an array: const int SIZE = 5; int array1[SIZE] = { 10,20,30,30,40 }; B.insert( array1, array1 + SIZE ); Find a value: multiset ::const_iterator I = B.find( 30 );

Copyright 2003, Kip R.Irvine31 Using typedef Use typedef to simplify type definitions: typedef multiset msetInt;. msetInt A; typedef multiset ::const_iterator msetIter;. msetIter = A.insert( 30 );

Copyright 2003, Kip R.Irvine32 Printing a Multiset template void print( const multiset & aSet ) { if ( aSet.empty() ) cout << "Set is empty"; else { multiset ::const_iterator I = aSet.begin( ); for( ; I != aSet.end( ); I++ ) cout << *I << ", "; }

Copyright 2003, Kip R.Irvine33 set Associative Container keys are unique attempt to insert duplicate key is ignored same functions as multiset

Copyright 2003, Kip R.Irvine34 map Associative Container unique keys and their associated values each key is mapped to a single value values do not have to be unique fast storage and retrieval sorted in order according to keys Iterators point to pair fields named first, second values can be inserted using [ ] operator see: mapdemo.cpp

Copyright 2003, Kip R.Irvine35 Function Objects template class that contains a function the function can be used in the same way as operator ( ) make STL more flexible permit sorting on your own criteria predefined objects in STL: divides equal_to greater greater_equal less etc.

Copyright 2003, Kip R.Irvine36 Function Object Example Default comparison of STL container objects when sorting uses the < operator: template class less { public: bool operator()(const T & x, const T & y) const { return x < y; } };

Copyright 2003, Kip R.Irvine37 Function Object Example When you declare a set, you have the option of specifying a function object that will determine the positions where new elements are inserted. Example: set of strings named myStringSet: set > myStringSet;

Copyright 2003, Kip R.Irvine38 Binary Function Example Base class binary_function defines overloaded ( ) operator with two arguments. This function object squares a value and adds it to a total: template class SumSquaresClass :public binary_function { public: const T operator( )( const T & total, const T & value ) { return total + value * value; } };

Copyright 2003, Kip R.Irvine39 Binary Function Example (cont) accumulate( first, last, startVal, pred ) The STL defines an accumulate function that accumulates a sum over a collection. the optional pred parameter can be a function or a function object vector v;... int sum = accumulate( v.begin( ), v.end( ), 0, SumSquaresClass () );

Copyright 2003, Kip R.Irvine40 Optional Information

Copyright 2003, Kip R.Irvine41 deque sequence container pronounced "deck" provides benefits of vector and list in the same container rapid indexed access (like vector) efficient insertion & deletion at its ends (like list) supports random-access iterators often used for FIFO queue noncontiguous memory layout

Copyright 2003, Kip R.Irvine42 Common deque operations push_back( ) push_front( ) pop_back( ) pop_front( ) size( ) operator [ ] at( )

Copyright 2003, Kip R.Irvine43 deque Example #1 Create a deque containing pointers to strings: deque mque; mque.push_back( new Message( "John", "How are you?" )); mque.push_back( new Message( "Sam", "What's happening?" )); mque.push_back( new Message( "Anne", "What's for dinner?" )); mque.push_back( new Message( "Bill", "Let's go surfing!" ));

Copyright 2003, Kip R.Irvine44 deque Example #1 Serve all messages from the front of the queue until the queue is empty: while( mque.size( ) > 0 ) { cout << **(mque.begin( )) << endl; mque.pop_front( ); } see dequeDemo.cpp

Copyright 2003, Kip R.Irvine45 The End