CSE 332: C++ STL containers Intro to the C++ Standard Template Library (STL)‏ The STL is a collection of related software elements –Containers Data structures:

Slides:



Advertisements
Similar presentations
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
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.
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.
Basic C++ Sequential Container Features
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Writing Your Own STL Container Ray Lischner
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.
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.
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
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.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
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.
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.
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.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
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.
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.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
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.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
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.
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)
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.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Object-Oriented Programming (OOP) Lecture No. 41
Vectors Holds a set of elements, like an array
Standard Template Library (STL)
ENERGY 211 / CME 211 Lecture 19 November 3, 2008.
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

CSE 332: C++ STL containers Intro to the C++ Standard Template Library (STL)‏ The STL is a collection of related software elements –Containers Data structures: store values according to a specific organization –Iterators Variables used to give flexible access to the values in a container –Algorithms Functions that use iterators to access values in containers Perform computations that modify values, or creates new ones –Function objects Encapsulate a function as an object, use to modify an algorithm The STL makes use of most of what we’ve covered –Extensive use of function and class templates, concepts The STL makes use of several new ideas too –typedefs, traits, and associated types

CSE 332: C++ STL containers Intro to C++ STL Containers Goals –See how STL containers are implemented –See how differences in implementation affect use We’ll cover several kinds –Focus on template concepts –And how each container’s concept relates to its implementation Example to the left prints v[0] is 1 v[1] is 2 v[2] is 4 #include using namespace std; int main (int, char *[]) { vector v; // This would be asking for trouble.... // v[0] = 1; v[1] = 2; v[2] = 4; //... but this works fine... v.push_back (1); v.push_back (2); v.push_back (4); //... and now this is ok... for (size_t s = 0; s < v.size(); ++s) { cout << "v[" << s << "] is " << v[s] << endl; } return 0; }

CSE 332: C++ STL containers template struct block{ // every iterator must have value, difference, reference and pointer types. typedef T value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef ptrdiff_t different_type; // should always be signed typedef size_t size_type; // should always be unsigned typedef pointer iterator; // iterator types typedef const_pointer const_iterator; }; From Matthew H. Austern, “Generic Programming and the STL” Example: C++ Array, type traits

CSE 332: C++ STL containers Containers Must Work with Iterators Declare appropriate iterator types (traits)‏ typedef pointer iterator; typedef const_pointer const_iterator; Provide iterator accessor/factory methods iterator begin() {return data;} iterator end() {return data+N;} const_iterator begin() const {return data;} const_iterator end() const {return data+N;} iterator rbegin() {return data+N-1;} iterator rend() {return data-1;} const_iterator rbegin() const {return data+N-1;} const_iterator rend() const {return data-1;}

CSE 332: C++ STL containers template struct block{ // typedef’s defining required types // define both mutable and const versions iterator begin() {return data;} const_iterator begin() const {return data;} iterator end() {return data+N;} const_iterator end() const {return data+N;} // accessor methods reference operator[](size_type n) {return data[n];} const_reference operator[](size_type n) const {return data[n];} size_type size() const {return N;} T data [N]; }; Example: Array-based STL Container

CSE 332: C++ STL containers Basic Requirements for an STL Container Contains elements: value semantics –Containers may not overlap –An element belongs to at most one container. may copy by value into other containers object ownership can not be shared –Object’s lifetime may not extend beyond that of the container. object created no earlier than when container is constructed contained object are destroyed when container is destroyed –Container may be fixed or variable size. Provide interfaces to contained values –Iterators with all elements contained in the range [A.begin(),A.end())‏ –must define ancillary types: value_type, pointer, const_pointer, reference, const_reference, difference_type and size_type. –Should obey the “principle of least surprise” For example a linked list would not provide [] Provide operations for a regular type –Assignable, Default Constructible, Equality Comparable

CSE 332: C++ STL containers Classifying containers Containers may be classified by the type of iterator: –Forward: supports forward iterators –Reversible: is a Forward Container whose iterators bidirectional iterators. A reversible container must define reverse_iterator, const_reverse_iterator and the methods rbegin() and rend(). Reverse iterator range [A.rbegin(),A,rend())‏ –Random Access: A reversible container whose iterators are random access iterators. It defines the operator operator[]().

CSE 332: C++ STL containers Container Forward Container Reversible Container Random Access Container Sequence (variable size)‏ Front Insertion Sequence Back Insertion Sequence Simple Associative Container Pair Associative container Unique Associative Container Sorted Associative Container Multiple Associative Container Hashed Associative Container Hierarchy of STL Container Concepts From: Matthew H. Austern, “Generic Programming and the STL” Associative (variable size)‏

CSE 332: C++ STL containers Container Forward Container Reversible Container Random Access Container Sequence Front Insertion Sequence Back Insertion Sequence General Container Concepts refined by models vector deque list Notice containers can have multiple classifications –Useful to look at differences between data structures! –Back vs. front insertion –Forward vs. reversible vs. random access More general concepts higher in the hierarchy More specific concepts appear farther down slist

CSE 332: C++ STL containers Container: Top of its Concept Hierarchy Valid ExpressionsComplexity –Copy constructor X(a) linear –Copy constructor X b(a) linear –Assignment operator b = a linear –Destructor a.~X() linear –Beginning of range a.begin() constant –End of range a.end() constant –Size a.size() linear -- O(N)‏ –Maximum size a.max_size() amortized, constant –Empty a.empty() amoritized, constant –Swap a.swap(b) linear – O(N) Container Invariants (for Container a): valid range: [a.begin(), a.end()), but order is not guaranteed Range size: a.size() == distance(a.begin(), a.end())‏ Completeness: Iterating through the range [a.begin(), a.end()) will access all elements.

CSE 332: C++ STL containers Container Container concept: –Owns elements that it stores. –Provides methods to access elements –Defines an associated iterator type –Requires iterator to model the input_iterator concept –Elements are unordered. –Only one active iterator permitted. –Refinement of Assignable Associated types: –value_type : must model Assignable –reference : usually value_type& –const_reference : usually const value_type& –pointer : usually value_type* –const_pointer : usually const value_type* –iterator : must model input iterator. Expected its value, reference and pointer types are the same as the containers. Its not required to be mutable. –const_iterator : value type is expected to be the containers value type (not const value_type). Reference and pointer types expected to be const versions of containers. –different_type : signed integral type, represents distance between iterarors. –size_type : unsigned integral represents >0 value of difference type.

CSE 332: C++ STL containers Forward Container Additional ExpressionsComplexity –Equality a == b linear –Inequality a != b linear –Less than a < b linear –Greater than a > b linear –Less than or equal a <= b linear –Greater than or equal a >= b linear Container Forward Container vector deque list slist Refinement of Container, Equality Comparable, LessThan Comparable equality semantics: sizes are equal and each element is equal Invariants (for Forward Container a): Ordering: ordering is consistent across accesses, providing no mutations of occurred.

CSE 332: C++ STL containers Reversible Container Additional ExpressionsComplexity –Beginning of reverse range a.rbegin() amortized constant –End of reverse range a.rend() amortized constant vector deque list Container Forward Container Reversible Container Refinement of Forward Container whose iterators are bidirectional. Introduces types: reverse_iterator and const_reverse_iterator Invariants: Valid range: [a.rbegin(), a.rend())‏ Equavalence of ranges: forward and reverse distance is the same.

CSE 332: C++ STL containers Random Access Container Additional ExpressionsComplexity –Element access a[n] Amortized constant Container Forward Container Reversible Container Random Access Container vector deque Refinement of Reversible Container whose iterator is Random Access.

CSE 332: C++ STL containers Sequence Additional ExpressionsComplexity –Fill constructor X(n,t) linear –Fill constructor X(n) (same as X(n,T()) linear –Default constructor X() (same as X(0,T()) linear –Range constructor X(i,j) linear –Insert a.insert(p,t) sequence-dependent –Fill insert a.insert(p,n,t) linear –Range insert a.insert(p,i,j) linear –Erase a.erase(p) sequence-dependent –Range erase a.erase(p,q) linear –Front a.front() amortized constant Container Forward Container Sequence vector deque list slist Refinement of Forward Container, Default Constructable Elements arranged in a strict order. After an insert operation iterators are not guaranteed to remain valid

CSE 332: C++ STL containers Front Insertion Sequence Additional ExpressionsComplexity –a.front()‏ –Push front a.push_front(t) constant –Pop front a.pop_front(t) constant Container Forward Container Sequence Front Insertion Sequence deque list slist

CSE 332: C++ STL containers Back Insertion Sequence Additional ExpressionsComplexity –Back a.back() constant –Push back a.push_back(t) constant –Pop back a.pop_back(t) constant vector deque list Container Forward Container Sequence Back Insertion Sequence

CSE 332: C++ STL containers Sequential Containers –vector: fast random access –list: fast insertion/deletion –deque: double-ended queue Sequential Containers Adaptors –stack: last in/first out stack –queue: First in/First out queue –priority queue: priority management Element types must support assignment and copy. Only vector and deque support subscripting

CSE 332: C++ STL containers Sequence s vector can be used as a stack: –push_back(), pop_back() –pop_back() does not return a value, must use back(). List operations –insert(), erase() and clear(). –not as efficient on vectors. –a list container is optimized for inserting and removing from arbitrary locations within the sequence. –adding/removing elements may invalidate iterator

CSE 332: C++ STL containers size and capacity the size() method returns the number of elements in the container the capacity() method indicates the maximum number of elements that can be stored in the current memory allocation – vector only. –capacity() – size() is the number of elments that can be added before memory must be reallocated. max_size() is the largest possible container of this type. calling resize() on a vector may move elements to another location invalidating any iterators. instantiating a container may result in a bad_alloc() exception vector v(10000);

CSE 332: C++ STL containers Container Simple Associative Container Pair Associative container Unique Associative Container Sorted Associative Container Multiple Associative Container Hashed Associative Container Associative Container Concepts Associative Container Forward Container set multiset map multimap hash_set hash_multiset hash_map hash_multimap refined by models

CSE 332: C++ STL containers Associative Container Additional Expressions Complexity –Default constructor X () constant –Default constructor X a; constant –Find a.find(k) logarithmic –Count a.count(k) O(log(size())+count(k))‏ –Equal range a.equal_range(k)) logarithmic –Erase key a.erase(k) O(log(size())+count(k))‏ –Erase element a.erase(p) constant –Erase range a.erase(p,q) O(log(size())+count(k))‏ set multiset map multimap hash_sethash_multiset hash_maphash_multimap

CSE 332: C++ STL containers Unique Associative Container Additional ExpressionsComplexity –Range constructor X a(i,j) linear –Insert element a.insert(t) logarithmic –Insert range a.insert(i,j) O(Nlog(size()+N))‏ setmap hash_set hash_map

CSE 332: C++ STL containers Multiple Associative Container Additional Expressions Complexity –Range constructor X a(i,j) linear –Insert element a.insert(t) logarithmic –Insert range a.insert(i,j) O(Nlog(size()+N)) multisetmultimap hash_multiset hash_multimap

CSE 332: C++ STL containers Sorted Associative Container Additional Expressions Complexity –Default constructors X (); X a; constant –Default constructor with comparator X a(c) constant –Range constructor X(i,j) O(NlogN)‏ –Range constructor w/ comparator X a(i,j,c) O(NlogN)‏ –Key comparison a.key_comp() constant –Value comparison a.value_comp() constant –Lower bound a.lower_bound(k) logarithmic –Upper bound a.upper_bound(k) logarithmic –Equal range a.equal_range(k) logarithmic –Insert with hint a.insert(p,t) logarithmic set multiset map multimap

CSE 332: C++ STL containers Hashed Associative Container Additional Expressions Complexity –Default constructors X (); X a; constant –Default constructor with bucket count X a(n) constant –Default constructor with hash function X a(n,h) constant –Default constructor with key equality X a(n,h,k) constant –Range constructor X a(i,j) linear –Range constructor with bucket count X a(i,j,n) linear –Range constructor w/ hash fxn X a(i,j,n,h) linear –Range constructor w/ key eq X a(i,j,n,h,k) linear –Hash function a.hash_funct() constant –Key equality a.key_eq() constant –Bucket count a.bucket_count() constant –Resize a.resize() linear hash_sethash_multiset hash_maphash_multimap

CSE 332: C++ STL containers Example Using map write a program that maps c-style strings for numbers specifying your own comparison operator ( < )‏ // define a functor for comparing c-style strings class CStringLess { public: bool operator()(const char *s1, const char *s2) { return strcmp(s1, s2) < 0; } }; // define convenience typedefs typedef map mapType; typedef mapType::value_type pairType; mapType tbl; // the table tbl["00"] = "Zero"; tbl["01"] = "One"; tbl["02"] = "Two"; tbl["03"] = "Three"; tbl["04"] = "Four"; tbl["05"] = "Five"; tbl["06"] = "Six"; tbl["07"] = "Seven";tbl["08"] = "Eight"; tbl["09"] = "Nine";

CSE 332: C++ STL containers continued Looking for a value mapType::const_iterator cit = tbl.find(“05”)‏ if (cit == tbl.end())‏ … found it … else … not found … Erase a value mapType::iterator iter = tbl.find(eraseVal); if (iter != tbl.end())‏ tbl.erase(iter); Inserting values using insert()‏ pair ret = tbl.insert(make_pair(eraseVal, "XXXXX")); if (ret.second)‏ std::cout << "Inserted entry: “ first << "\n";

CSE 332: C++ STL containers Student Records Num LastName FirstName MName StdtId DropCd Score Grade 1) Alhaddad Lorinda Hang EN 87 B 2) Asnicar Reynalda Phebe EN 97 A 3) Baudino Ernesto Rex WD -1 NG 4) Bock Ester Jimmy EN 88 B 5) Bonavita Elias Johnathan EN 71 C 6) Botti Maybell Shawnta EN 27 F 7) Dailey Kyle Quinn DP -1 NG 8) Debellis Rusty Gale EN 85 B 9) Duldulao Sherman Orlando EN 95 A 10) Hertweck Carmelo Garret EN 80 B 11) Laughead Troy Kirby EN 39 F 12) Lieuallen Cristen Erma EN 93 A 13) Malsom Anton Darrell EN 72 C 14) Mcbrayer Jerald Wendell DP -1 NG 15) Myer Brandie Aleen EN 92 A 16) Schmid Tarsha Louis EN 83 B 17) Siroka Odis Tom WD -1 NG 18) Tutaj Keva Venessa EN 88 B 19) Ventrella Jene Reita EN 83 B 20) Waz Nereida Sherill EN 85 B

CSE 332: C++ STL containers Example using multimap typedef vector record_t; typedef vector roster_t; roster_t roster; map nameMap; multimap gradeMap; // Now get roster records while (getline(fin, line)) { vector fields; // skip blank lines if (string2flds(fields, line, "\t", " \n\r") == 0)‏ continue; // create student record, ignoring first field record_t rec(fields.begin()+1, fields.end()); roster.push_back(rec);

CSE 332: C++ STL containers continued { // … loop reading records // Add to name to roster mapping nameMap[fullName] = roster.back(); // Add to grade to roster mapping gradeMap.insert(make_pair(rec[Grade], rec)); } // print the number of students receiving an A cout << "Students getting an A (" << gradeMap.count("A") << ")\n"; // print names of students receivign an A multimap ::const_iterator iter = gradeMap.lower_bound("A"); for (; iter != gradeMap.upper_bound("A"); ++iter)‏ cout second[LastName] second[FirstName] << endl; // All students map ::const_iterator iterx = nameMap.begin(); for (; iterx != nameMap.end(); ++iterx)‏ cout second[LastName] << endl;