The Standard Template Library Container Classes Version 1.0.

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 6 Queues and Deques.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Week 5 - Associative Containers: sets and maps. 2 2 Main Index Main Index Content s Content s Container Types Sequence Containers Adapter Containers Associative.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
 2006 Pearson Education, Inc. All rights reserved Templates.
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.
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)
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.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Standard Template Library Programming paradigm: generic programming the decomposition of programs into components which may be developed separately and.
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.
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.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 18.1 Iterators 18.2 Containers 18.3 Generic Algorithms Slide
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
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)
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,
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.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
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.
Data Structures for Midterm 2. C++ Data Structure Runtimes.
A gentle introduction to the standard template library (STL) Some references:
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
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.
Vectors. Basics A vector is like an array, but more flexible A vector provides (constant time) random access to its elements A vector may be dynamically.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Standard Template Library a collection of useful tools.
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)
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Copyright © – Curt Hill STL List Details Copyright © – Curt Hill.
Iterators and STL Containers
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

The Standard Template Library Container Classes Version 1.0

The Standard Template Library provides a set of template classes designed to help you organize data in various useful ways. These are called containers or sometimes they are called collection classes.

There are two general kinds of containers: Sequential Containers Associative Containers

Sequence Containers Sequence containers are ordered collections Every element has a certain position Position depends on time and place of insertion There are three predefined sequence containers: Vector Deque List

Associative Containers Associative containers are sorted collections The position of an element depends upon its value Position is independent of the order of insertion There are four predefined associative containers: Set Multi-set Map Multi-map

Common Container Abilities All containers provide value rather than reference semantics. That is, containers copy elements internally when they are inserted, rather than managing references to them. Thus, each element in a container must have a public copy constructor.

Common Container Abilities All containers have an order. Each container provides functions that return an iterator that can be used to move through the elements in the container in order.

Common Container Abilities In general, operations on containers are not safe. It is the programmer’s responsibility to make sure that all parameters of an operation are valid and meet the requirements of the operation. Violating these requirements will result in an undefined behavior. Usually the STL does not throw exceptions!

Common Operations All container classes provide the following: OperationEffect CType c creates an empty container CType c1(c2) creates a container c1, copying c2 into it (c1 and c2 are the same type of container)

Initialization Every container class comes with a default constructor, a copy constructor, and a destructor. Constructors are provided to initialize a container with the elements of another container or from an array.

vector v; create an empty vector list l;... vector v(l.begin( ), l.end( )); create a vector and initialize it from a list int array[ ] = { 2, 17, 23, 46, 22};... vector v(array, array+sizeof(array)/sizeof(array[0]) ); create a vector and initialize from an array

Common Operations All container classes provide the following: OperationEffect CType c creates an empty container CType c1(c2) creates a container c1, copying c2 into it c.size( )returns the number of elements in c c.empty( )returns true if the container c is empty c.max_size( )returns the maximum number of elements ever possible c1 == c2returns true if the containers of the same type are equal c1 != c2returns true if the containers are not equal

Comparison operations are defined based on the following three rules: 1. Both containers are of the same type 2. Two containers are equal if their elements are equal and have the same order. 3. Lexicographical comparison is done to see if one container is less (or greater) than another.

Common Operations All container classes provide the following: OperationEffect c1.swap(c2) swaps the data in c1 and c2 (c1 and c2 are of the same type) c.begin( ) returns an iterator for the first element in c c.end( ) returns a sentinel marking the last element in c c.rbegin( ) returns a reverse iterator for the last element in c c.rend( ) returns a sentinel marking the first element in c c.clear( ) erases all elements from c - makes the container empty c.~CType ( ) destroys all elements and frees the memory

Efficiency of operations Operation vector list deque Constructor( ) O(1) O(1) O(1) Constructor(size) O(1) O(n) + O(1) Constructor(size, value) O(n) O(n) O(n) at(int) O(1) --- O(1) push_back(value) O(1) + O(1) O(1) + begin( ) / end( ) O(1) O(1) O(1) operator[ ] O(1) --- O(1) O(1) – independent of the number of elements O(n) – linear, depends on the value of n

Vectors Vectors store their elements in an internal dynamic array. You can access any element of a vector in constant time provided you know where the element is. Vectors provide good performance when adding or deleting elements at the end, but inserting or deleting in the middle is very expensive. This is because every element behind has to be moved to a new position. Insertion time is not constant! Vectors grow as required, but “growing” a vector is expensive, and invalidates all references, pointers and iterators for elements of the vector

Assignments Assignment (e.g. c1 = c2) is very expensive for any container class. Every element of the left container is destroyed and a copy made of every element of the right container. The default constructor, copy constructor, and overloaded assignment operators are used for each element in the copied container.

If you don’t need to re-use the source container, then the swap( ) function is much more efficient than doing an assignment, as it only swaps pointers. It does not make a copy.

Element Access OperationEffect c.at(idx)returns the element at index idx. Throws an exception if idx is out of range c[idx]returns the element at idx, no range checking c.front( )returns the first element (no check to see if one exists) c.back( )returns the last element (no check to see if one exists)

Inserting and Deleting Elements There are a number of operations defined to insert and delete elements from a Vector.

Inserting and Deleting Elements Operation Effect c.insert(pos,elem) inserts a copy of elem at pos and returns the position of the new element (pos is an iterator). c.push_back(elem) adds a copy of elem at the end of the vector c.pop_back( ) removes the last element in the vector c.erase(pos) removes the element at position pos and returns the position of the next element. c.resize(num) changes the size of the vector to num. Calls the default constructor for new elements. iterators must refer to valid positions. Do not try to remove an element from an empty container.

vector v vector ::iterator p vector ::iterator vp = v.insert(p, 27);

vector v vp vector ::iterator vp = v.insert(p, 27); 27

#include using namespace std; int main ( ) { vector sentence; sentence.reserve(10); sentence.push_back("Hello,"); sentence.push_back("how"); sentence.push_back("are"); sentence.push_back("you?"); vector ::iterator p; for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << " "; cout << endl; system("PAUSE"); return 0; }

Deques Pronounced “deck”, a Deque is similar to a vector. It manages its elements with a dynamic array It provides random access A deque allows insertions and deletions at both ends, Which is fast. Insertion into the middle is slow. Element access and iterator movement is a bit slower than with a vector. Deques do not support the functions capacity( ) and reserve( )

Grows like a vector – but in both directions

Choose a deque if … You need to insert or delete from either end of the container You do not need to randomly access data in the container

Inserting and Deleting Elements Operation Effect c.insert(pos,elem) inserts a copy of elem at pos and returns the position of the new element. c.push_back(elem) adds a copy of elem at the end of the deque c.pop_back( ) removes the last element in the deque c.push_front(elem) adds a copy of elem at the front of the deque c.pop_front( ) removes the first element in the deque iterators must refer to valid positions. Do not try to remove an element from an empty container. new

The assign function void container::assign(size_type num, const T& value); The assign function replaces all existing elements of the container with num occurences of value.

#include using namespace std; int main ( ) { deque sentence; sentence.assign(3, string("middle stuff") ); sentence.push_back("end string"); sentence.push_front("front_string"); deque ::iterator p; for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << "\n "; cout << endl; system("PAUSE"); return 0; }

Lists Lists are very different from vectors and deques A list does not provide random access. accessing an arbitrary element is slow. Inserting and deleting elements is fast at any position, not just the first and last. Inserting and deleting elements does not invalidate pointers, references, or iterators. Lists have the best exception safety of all of the STL containers. Either an operation works or it is a no-op in almost all cases.

Element Access Because a list does not support random access, only the following functions are provided for direct access: c.front( ) c.back( ) All other access must be done through iterators. Only bi-directional iterators are supported. Thus, you cannot call algorithms that require random access iterators. Sorting algorithms fall in this category.

Inserting and Deleting Elements Operation Effect c.insert(pos,elem) inserts a copy of elem at pos and returns the position of the new element. c.push_back(elem) adds a copy of elem at the end of the deque c.pop_back( ) removes the last element in the deque c.push_front(elem) adds a copy of elem at the front of the deque c.pop_front( ) removes the first element in the deque r.remove(val) removes all elements with the value val r.remove_if(op) removes all elements for which op(elem) is true iterators must refer to valid positions. Do not try to remove an element from an empty container. new

Splice Functions Linked lists have the advantage that you can insert and delete elements at any point in the list in constant time. Lists support a number of unique functions to change the order of and re-link elements in a list.

Splice Functions Linked lists have the advantage that you can insert and delete elements at any point in the list in constant time. Lists support a number of unique functions to change the order of and re-link elements in a list. This is accomplished by manipulating pointers

Operation Effect c.unique( ) removed duplicates of consecutive elements c1.splice(pos, c2) moves all elements of c2 to c1 in front of the iterator position pos c1.splice(pos, c2, c2p) moves the element at c2p to c1 in front of the iterator position pos c1.splice(pos, c2, c2b, c2e) moves all elements in the range [c2b, c2e] in c2 to c1 in front of the iterator position pos c.sort( ) sorts all elements of c using < c.sort(op) sorts all elements of c using op( ) c1.merge(c2) assuming that c1 and c2 are sorted, moves all elements of c2 into c1 so that the resulting list is still sorted

#include using namespace std; int main ( ) { list sentence; sentence.assign(3, string("middle stuff") ); sentence.push_back("end string"); sentence.push_front("front_string"); list ::iterator p; for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << "\n"; cout << endl; system("PAUSE"); return 0; }

cout << "\n\nSorted List\n\n"; sentence.sort( ); for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << "\n"; cout << endl;

Sets and Multisets Sets and multisets sort their elements automatically according to a certain sorting criteria. Multisets allow duplicate elements, while sets do not. The sorting criteria must define strict weak ordering: It has to be antisymmetric for <, if x < y is true, then y < x is false It has to be transitive for <, if x < y is true and y < z is true, then x < z is true It has to be irreflexive for <, x < x is always false

Set Multiset

Sets and multisets are usually stored internally as balanced binary trees. (You will learn about trees in data structures.)

Sets and multisets do not provide any operations for direct element access. You may not change the value of an element directly because this may affect the ordering. You have to remove the element that has the old value and insert the element with the new value.

Constructors OperationEffect set c A set that sorts with < operator set c A set that sorts with op multiset c A multiset that sorts with < operator multiset c A multiset that sorts with op set > collection;

Special Search Operations Operation Effect count (elem) returns the number of elements with value elem find (elem) returns the position of the first element with value elem

Inserting and Removing Elements Operation Effect c.insert(elem) inserts a copy of elem and returns the position (and for sets whether or not it succeeded) c.insert(pos, elem) inserts a copy of elem, using pos as a hint of where c.erase(elem) removes all elements of value elem c.Erase (pos) removes the element at pos c.clear( ) removes all elements from the set

Iterators Iterators are bidirectional, and can’t be used in algorithms the require random access. Most importantly, from the iterator’s point of view, all elements are considered constant. Thus you cannot use an iterator in any modifying algorithm on elements of a set or a multiset.

#include using namespace std; int main ( ) { set nums; nums.insert(17); nums.insert(3); nums.insert(12); nums.insert(6); nums.insert(3); set ::iterator p; for (p = nums.begin( ); p != nums.end( ); p++) cout << *p << "\n"; cout << endl; system("PAUSE"); return 0; }

note that the values are in order. and 3 only appears once.

Maps and Multimaps Maps and multimaps mange key/data pairs as elements and sort their contents automatically according to a certain sorting criteria that is used for the actual key.

2 x 1 y 4 z 5 y key value

Constructors Operation Effect map c A map that sorts keys with < operator map c A map that sorts keys with op multimap c A multimap that sorts keys with < operator multimap c A multimap that sorts keys with op

Special Search Operations OperationEffect count (k)returns the number of elements with key k find (k) returns the position of the first element with key k

Iterators Iterators are bidirectional, and can’t be used in algorithms that require random access. Most importantly, from the iterator’s point of view, all elements are considered constant. Thus you cannot use an iterator in any modifying algorithm on elements of a map or a multimap.

Maps as Associative Arrays Non-constant maps provide a subscript operator for direct element access. However, the index of the subscript operator is not the integer position of the element, but it is the key that is used to identify the element.

#include using namespace std; int main ( ) { map stocks; stocks["GM"] = ; stocks["Ford"] = ; stocks["BMW"] = ; stocks["Audi"] = ; map ::iterator p; for (p = stocks.begin( ); p != stocks.end( ); p++) cout first second << "\n"; cout << "\n\n" << stocks["Audi"]; cout << endl; system("PAUSE"); return 0; } key data

sorted by key

When to Use Which Container characteristic vector deque list set map internal store dynamic array array of arrays binary tree binary tree binary tree elements value value value value key/value pair random access yes yes no no no iterator category random access random access bidirectional bidirectional bidirectional search/find elements slow slow very slow fast fast for key insert/remove at the back at front & back anywhere elements insert/remove on reallocation always never never never invalidates pointers, references, & iterators

Container Adapters Container adapters modify the standard containers to fit special needs. Stacks Queues Priority Queues

Stack A stack is a first-in, last-out container. It provides the following interface: OperationEffect push( ) inserts an element into the stack pop( ) removes an element from the stack top( ) returns the top element in the stack push pop top

Queue A queue is a first-in, first-out container. It implements the following interface: OperationEffect push( ) inserts an element into the queue front( ) returns the next element in the queue pop( ) removes an element from the queue back ( ) returns the last element push pop back front

Priority Queue A priority queue is a queue from which elements are read in priority order. OperationEffect push( ) inserts an element into the queue top( ) returns the highest priority element in the queue pop( ) removes an element from the queue push pop top elements are prioritized according to their value

Bitsets Bitsets are fixed sized arrays of bits, or boolean values. They are useful for managing sets of flags