Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.

Slides:



Advertisements
Similar presentations
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Advertisements

. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
More on the STL vector list stack queue priority_queue.
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.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
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
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.
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
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.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 18.1 Iterators 18.2 Containers 18.3 Generic Algorithms Slide
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)
The C++ Standard Template Library. What is STL A subset of the standard C++ library –The string class is not part of it! 3 major components –Algorithms.
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.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
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.
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.
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:
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.
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.
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.
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.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
CHAPTER 11 CS 3370 – C++ Associative Containers. The ordered containers used tree-based storage O(log n) retrieval complexity The unordered containers.
Introduction to olympic programming
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
Elements are always copied when they are put into a container
Lists - I The List ADT.
Lists - I The List ADT.
Iterators and STL Containers
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.
The List Container and Iterators
Standard Template Library
Presentation transcript:

Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.

All Containers... Are homogeneous Provide insert and erase capability –grow as needed Support the following methods: size_type size() const; size_type max_size() const; bool empty() const;

Standard Containers Sequences –vector, deque, list Container Adapters –queue, stack, priority_queue Associative Containers –set, multiset, map, multimap

A First Look A set example –IntSet.cpp –WordSet.cpp A vector example: –StringVector.cpp

Sequences vector –random access –optimal insertion/deletion at end ( push_back ) deque –random access –optimal insertion/deletion at both ends ( push_front ) list –sequential access only –doubly-linked; optimal insertion/deletion anywhere

All Sequences support... void resize(size_type, T = T()); T& front() const; T& back() const; void push_back(const T&); void pop_back();

Restricted Sequence Functions // deque and list only: void push_front(const T&); void pop_front(); //deque and vector only: T& at(size_type n);

Nagging Questions How does one navigate a list ? –It doesn’t have any traversal member functions! How does one use the standard algorithms on a sequence? –Don’t tell us that all the algorithms have to be repeated as member functions! The answer is…

Iterators Generalization of a pointer Overload at least operator!=, operator==, operator*, operator++, operator-> Some overload operator--, operator[]

Traversing a List list lst; … // insert some elements, then: list ::iterator p = lst.begin(); while (p != lst.end()) { // Process current element (*p), then: ++p; } All sequences provide members begin and end

Implementing find template Iterator find(Iterator start, Iterator past, const T& v) { while (start != past) { if (*start == v) break; ++start; } return start; } All algorithms are implemented in terms of iterators

Iterator Taxonomy Input Output Forward Bi-directional Random Access

Input Iterators Read-only access to elements Single-pass, forward traversal find expects an Input Iterator

The Real Implementation of find (Documentation change only) template InputIterator find(InputIterator start, InputIterator past, const T& v) { while (start != past) { if (*start == v) break; ++start; } return start; }

Output Iterators Write-only access to elements Single-pass, forward traversal Example: ostream_iterator: copy(a, a+n, ostream_iterator (cout,“ “));

Forward Iterators Both read and write access –can therefore substitute for Input or Output Iterators Multiple-pass forward traversal unique expects a Forward Iterator list ::iterator p = unique(lst.first(), lst.end());

Bi-directional Iterators Can do everything a Forward Iterator can Also support backwards traversal –operator--() –operator--(int) reverse requires a Bi-directional Iterator

Traversing a List Backwards list::iterator p = lst.end(); while (p > lst.begin()) { --p;// “advances” backwards // process *p, then: if (p == lst.begin()) break; }

A Better Way Reverse Iterators list::reverse_iterator p = lst.rbegin(); while (p != lst.rend()) { // process *p, then: ++p;// “advances” backwards }

Random Access Iterators Support Pointer Arithmetic in constant time –operator+, +=, -, -=, [],, >= sort expects a Random Access Iterator

How do you Sort a List? Doesn’t provide a Random Access Iterator Generic sort will fail on a list Provides its own sort member function Also merge, remove, and unique

What’s Wrong with this Picture? vector v1; … // fill v1, then: vector v2; copy(v1.begin(), v1.end(), v2.begin());

Iterator Modes Iterators work in overwrite mode by default Need an insert mode for cases like above –that calls appropriate, underlying insert operation

Insert Iterators Replace output calls ( operator*, operator=, etc.) with appropriate insert function back_insert_iterator –calls push_back front_insert_iterator –calls push_front insert_iterator –calls insert

Helper Functions back_inserter –creates a back_insert_iterator front_inserter –creates a front_insert_iterator inserter –creates an insert_iterator

Insert Iterator Example vector v1; … // fill v1, then: vector v2; copy(v1.begin(), v1.end(), back_inserter(v2));

Stream Iterators ostream_iterator –an Output Iterator copy(v1.begin(), v1.end(), ostream_iterator (cout, “ “)); istream_iterator –an Input Iterator copy(istream_iterator (cin), istream_iterator (), back_inserter(v1));

Container Adapters High-level abstract data types –queue, stack, priority_queue Use a sequence for implementation stack > myStack; stack & queue use deque by default priority_queue uses a vector No iterators are provided –more restricted interface

Associative Containers set stores unique elements test for membership multiset allows duplicates map stores pairs keys must be unique multimap allows duplicate keys Support fast (logarithmic), key-based retrieval Stored according to an ordering function less () by default can use as a sequence

Set Example #include using namespace std; void main() { // Populate a set: set s; s.insert("Alabama"); s.insert("Georgia"); s.insert("Tennessee");

// Print it out: set ::iterator p = s.begin(); while (p != s.end()) cout << *p++ << endl; cout << endl; // Do some searches: string key = "Alabama"; p = s.find(key); cout << (p != s.end() ? "found " : "didn't find ") << key << endl; key = "Michigan"; p = s.find(key); cout << (p != s.end() ? "found " : "didn't find ") << key << endl; }

// Output: Alabama Georgia Tennessee found Alabama didn't find Michigan

Map Example #include using namespace std; void main() { // Convenient typedefs: typedef map > map_type; typedef map_type::value_type element_type;

// Insert some elements (two ways): map_type m; m.insert(element_type(string("Alabama"), string("Montgomery"))); m["Georgia"] = "Atlanta"; m["Tennessee"] = "Nashville"; m["Tennessee"] = "Knoxville"; // Print the map: map_type::iterator p = m.begin(); while (p != m.end()) { element_type elem = *p++; cout << '{' << elem.first << ',’ << elem.second << "}\n"; } cout << endl;

// Retrieve via a key: cout << '"' << m["Georgia"] << '"' << endl; cout << '"' << m["Texas"] << '"' << endl; } // Output: {Tennessee,Knoxville} {Georgia,Atlanta} {Alabama,Montgomery} "Atlanta” ""

Word Count Example Shows the conciseness of map’s design Count the number of each word in a text file WordCount.cpp

Strict Weak Orderings Associative containers (set, map, multi_set, multi_set) require comparators that define a strict weak ordering –Like less ( ) (which calls operator<( )) –Never use <= or anything like it! Definition: f(x,y) is a s.w.o if: –f(x,x) = false(irreflexive) –f(x,y) = !f(y,x)(anti-symmetric) –f(x,y) && f(y,z) => f(x,z)(transitive)

Equivalence vs. Equality Equality uses operator== –Used by most algorithms (find, etc.) Equivalence is based on a s.w.o, f( ) –x and y are equivalent iff !f(x,y) && !f(y,x) –That’s how set and map decide whether an element is already in there or not –Example: ignoring non-alpha characters in a string –See swo.cpp

Applications

Grid A Sample Application Graphs y = f(x) Models the x-y plane as rows of characters In other words, a vector of vectors of char Illustrates insert iterators, reverse iterators, random acccess iterators, stream iterators, fill_n(), fill(), for_each(), copy() See grid.cpp

Grid Output | * | | * | | * | | * | ** ****

Duplicate Word Filter Like UNIX’s uniq Except it processes unsorted sequences Need a way to detect duplicate lines without disturbing original line order Illustrates ordering predicates, index vectors, generate_n(), stable_sort(), sort(), insert iterators, stream iterators, uniq() See uniq2.cpp –Data on next slide

Sample Data Input each peach pear plum i spy tom thumb tom thumb in the cupboard i spy mother hubbard Output each peach pear plum i spy tom thumb in the cupboard mother hubbard

uniq2 What data structure(s)? –Why won’t a set suffice? Accesses lines through an index Sorts the index based on line content, then removes adjacent duplicates with the unique algorithm Re-sorts the surviving indexes numerically to adhere to original order