Sets and Maps Andy Wang Data Structures, Algorithms, and Generic Programming.

Slides:



Advertisements
Similar presentations
Lists: An internal look
Advertisements

. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
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.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
. 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.
. 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.
CSE 332: C++ Associative Containers II Associative Containers’ Associated Types Associative containers declare additional types –A key_type gives the type.
Templates and the STL.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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 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.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generic Positional Containers and Double-Ended Queues.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
Generic Programming Using the C++ Standard Template Library.
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.
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,
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
A Generic List Class and Linked Lists Andy Wang Data Structures, Algorithms, and Generic Programming.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
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.
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
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.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
STL Containers Inside Peter Sikachev Institute of Computer Graphics and Algorithms Vienna University of Technology.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Associative Containers Sets Maps Section 4.8. Associative 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.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Main Index Contents 11 Main Index Contents Sets Defined by a key along with other data Sets Defined by a key along with other data Key-Value Data Key-Value.
CPSC 252 Tables / Maps / Dictionaries Page 1 Tables, Maps and Dictionaries A table (or map or dictionary) is a collection of key/value pairs. In general.
1 Designing Hash Tables Sections 5.3, 5.4, 5.5, 5.6.
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
1 Generic Positional Containers and Double-Ended Queues.
Standard Template Library (STL)
Andy Wang Data Structures, Algorithms, and Generic Programming
What remains Topics Assignments Final exam
Chapter 9 – Sets and Maps 9.1 Associative Container
structures and their relationships." - Linus Torvalds
Associative Structures
Trees 1: Theory, Models, Generic Heap Algorithms, Priority Queues
Generic Positional Containers and Double-Ended Queues
A Sorted, Unique Key Container
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Lists - I The List ADT.
Lists - I The List ADT.
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Recitation Outline Hash tables in C++ STL Examples Recursive example
structures and their relationships." - Linus Torvalds
Chapter 9 – Sets and Maps 9.1 Associative Container
Generic Set Algorithms
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

Sets and Maps Andy Wang Data Structures, Algorithms, and Generic Programming

Sets Abstract associative containers Abstract associative containers Set Set Stores objects Stores objects Unimodal: duplicate objects not allows Unimodal: duplicate objects not allows MultiSet MultiSet Stores objects Stores objects Multimodal: duplicate objects OK Multimodal: duplicate objects OK Also known as bags Also known as bags

Maps Abstract associative containers Abstract associative containers Map Map Stores (key, object) pairs Stores (key, object) pairs Unimodal: duplicate keys not allows Unimodal: duplicate keys not allows AKA: table, associative array AKA: table, associative array MultiMap MultiMap Stores (key, object) pairs Stores (key, object) pairs Multimodal: duplicate keys OK Multimodal: duplicate keys OK

Client Needs Insert an object Insert an object Remove a specified object Remove a specified object Remove all copies of an object Remove all copies of an object Inspect an object Inspect an object Iterate through all objects Iterate through all objects Optional Optional Performance constraints Performance constraints Iteration order constraints Iteration order constraints

Client Does Not Need Implementation details Implementation details Data structure used to implement the container Data structure used to implement the container

Example Set Clients Inventory Inventory struct StockItem { // barcode, name, amount }; void print_inventory(std::ostream&os, const set & inventory) { set<StockItem>::Iterator; for (I = inventory.Begin(); I != inventory.End(); ++I) { os << *I; }}

Example Set Clients Customer accounts Customer accounts class Customer { // ssn, account_number, last_name, first_name… }; int main() { set customers; }

Example Set Clients Exceptional instances Exceptional instances set dictionary; set wordset; set unknown = wordset – dictionary; for (set ::Iterator I = unknown.Begin(); I != unknown.End(); ++I) { std::cout << *I << endl; // output possible mispelled words }

Example Set Clients Instances in common Instances in common set S1, S2; set S = S1 * S2; // S contains the widgets that are in both S1 and S2

Example Set Clients Password server Password server struct User { String username; unsigned long signature; }; class PWServer { set users; …};

Example Set Clients Password server Password server int PWServer::CheckPW(const String uid, const String pw) { String uid_pw(uid + pw); unsigned long hash = secure_hash_function(uid_pw); User u(uid, hash); set ::Iterator I = users.Includes(u); if ((*I).username == u.username) && (*I).signature == user.signature)) { return 1; } return 0; }

Example Set Clients Any map client Any map client typedef set > map ; typedef set > map ;

Example Map Clients Password server Password server typedef String username; typedef unsigned long signature; class PWServer { map users; …}; int PWServer::CheckPW(const String & uid, const String &pw) { unsigned long hash = secure_hash_function(uid + pw); map :: Iterator I = users.Includes(uid); if (I.Valid() && (*I).key == uid && (*I).value = signature) { return 1; } return 0; }

Example Map Clients Internet router Internet router map routemap; Dictionary Dictionary map dictionary; Keyword index Keyword index map > concordance;

Set Tools (Sorted) Sorted sets Sorted sets CSet adaptor CSet adaptor Classic choices for C: sorted list, binary search tree, or red- black tree Classic choices for C: sorted list, binary search tree, or red- black tree Adaptation of sorted associative container Adaptation of sorted associative container Search operations: LowerBound(), UpperBound(), and Includes() Search operations: LowerBound(), UpperBound(), and Includes() Sorted order traversal Sorted order traversal Operators: union, intersection, difference, subset Operators: union, intersection, difference, subset Modality determined by adaptee Modality determined by adaptee

Map Tools (Sorted) Sorted maps Sorted maps CMap and CMultiMap adaptors CMap and CMultiMap adaptors Adaptation of sorted associative container Adaptation of sorted associative container Search operations: LowerBound(), UpperBound(), and Includes() Search operations: LowerBound(), UpperBound(), and Includes() Sorted order traversal Sorted order traversal Generic set algorithms apply Generic set algorithms apply Modality determined by adaptor Modality determined by adaptor

Set and Map Tools (Sorted) Client usage Client usage CSet > S1; CSet > S1; Sorted list Sorted list Unimodal Unimodal CSet > > S2; CSet > > S2; Sorted list in reverse order Sorted list in reverse order Multimodal Multimodal CMap > > S3 CMap > > S3 Sorted list Sorted list Unimodal Unimodal

Set and Map Tools (Sorted) typedef String key_type; typedef int data_type; typedef TAssociation pair_type; typedef special_class predicate_type; typedef TMBST container_type; CMultiMap M1; Binary search tree Binary search tree Multimodal Multimodal Special predicate class Special predicate class

Set and Map Tools (Unsorted) Unsorted sets and maps Unsorted sets and maps CHashSet, CHashMultiSet adaptors CHashSet, CHashMultiSet adaptors CHashMap, CHashMultiMap adaptors CHashMap, CHashMultiMap adaptors Adaption as vector of containers Adaption as vector of containers Search operation: Includes() Search operation: Includes() Random order traversal Random order traversal Modality determined by adaptor Modality determined by adaptor

The CSet Adaptor template template class CSet { friend class CSetIterator ; public: typedef T value_type; typedef C container_type; typedef C container_type; typedef CSetIterator Iterator; // constructors CSet() : c() { } CSet(const CSet & S) : c(S.c) { } ~CSet() { Clear(); } CSet &operator=(const CSet & S) { if (this != &S) { c = S.c; } return *this; }

The CSet Adaptor // element operations Iterator Insert(const value_type& t) { CSet ::Iterator I; I.i = c.Insert(t); return I; } int Insert(Iterator& I, const value_type& t) { return c.Insert(I.i, t); } size_t Remove(const value_type& t) { return c.Remove(t); } int Remove(Iterator& I) { return c.Remove(I.i); } void Clear() { c.Clear(); }

The CSet Adaptor // locator operations Iterator LowerBound(const value_type& t) const { CSet ::Iterator I; I.i = c.LowerBound(t); return I; } Iterator UpperBound(const value_type& t) const { CSet ::Iterator I; I.i = c.UpperBound(t); return I; } Iterator Includes(const value_type& t) const { CSet ::Iterator I; I.i = c.Includes(t); return I; }

The CSet Adaptor Iterator Begin() const { CSet ::Iterator I; I.i = c.Begin(t); return I; } Iterator End() const { CSet ::Iterator I; I.i = c.End(t); return I; } Iterator rBegin() const { CSet ::Iterator I; I.i = c.Begin(t); return I; } Iterator rEnd() const { CSet ::Iterator I; I.i = c.rEnd(t); return I; }

The CSet Adaptor // size operations int Empty() const { return c.Empty(); } size_t Size() const { return c.Size(); } protected: C c; };

Global Operators on CSet // containment operators bool operator & S1, const CSet & S2) { return g_subset_of(S1.Begin(), S1.End(), S2.Begin(), S2.End(); } bool operator & S1, const CSet & S2) { return (S1.Size() < S1.Size() && S1 <= S2); } bool operator>=(const CSet & S1, const CSet & S2) { return S2 <= S1; } bool operator>(const CSet & S1, const CSet & S2) { return S2 < S1; }

Global Operators on CSet // union CSet operator+(const CSet & S1, const CSet & S2) { CSet S; InsertIterator > I(S); g_set_union(S1.Begin(), S1.End(), S2.Begin(), S2.End(), I); return S; } // difference CSet operator-(const CSet & S1, const CSet & S2) { CSet S; InsertIterator > I(S); g_set_difference(S1.Begin(), S1.End(), S2.Begin(), S2.End(), I); return S; }

Global Operators on CSet CSet operator*(const CSet & S1, const CSet & S2) { CSet S; InsertIterator > I(S); g_set_intersection(S1.Begin(), S1.End(), S2.Begin(), S2.End(), I); return S; } bool operator==(const CSet & S1, const CSet & S2) { if (S1.Size() != S2.Size()) { return 0; } CSet ::Iterator I1(S1), I2(S2); while (I1.Valid() { if (*(I1++) != *(I2++)) { return 0; }} return 1; }

Global Operators on CSet bool operator!=(const CSet & S1, const CSet & S2) { return !(S1 == S2); } template template std::ostream operator & S) { CSet ::Iterator I; for (I = S.Begin(); I != S.End(); ++I) { os << *I; } return os; }

The CSetIterator Adaptor template template class CSetIterator { friend class CSet ; public: // constructors CSetIterator() : i() { } CSetIterator(const CSet & S) : i() { i = S.c.Begin(); } CSetIterator(const CSetIterator & I) : i(I.i) { } // initializers void Initialize(const CSet & S) { i.Initialize(S.c); } void rInitialize(cocnst CSet & S) { i.rInitialize(S.c); } // informationals value_type& Retrieve() const { return i.Retrieve(); } int Valid() const { return i.Valid(); }

The CSetIterator Adaptor // operators int operator==(const CSetIterator & I2) const { return i == I2.i; } int operator!=(const CSetIterator & I2) const { return i != I2.i; } value_type& operator*() const { return *i; } CSetIterator & operator=(const CSetIterator &I) { i = I.i; return *this; } CSetIterator & operator++() { ++i; return *this; } CSetIterator & operator++(int) { CSetIterator I = *this; CSetIterator ::operator++(); return I; }

The CSetIterator Adaptor CSetIterator & operator--() { --i; return *this; } CSetIterator & operator--(int) { CSetIterator I = *this; CSetIterator ::operator--(); return I; }protected: typename C::Iterator i; };

The CMap Adaptor template template class CMap { friend class CMapIterator ; public: typedef K key_type; typedef C container_type; typedef typename C::value_type value_type; typedef CMapIterator Iterator; // proper type CMap() : c() { } CMap(const CMap & M) : c(M.c) { } ~CMap() { c.Clear(); } CMap& operator=(const CMap & M) { if (this != M) { c = M.c; } return *this; }

The CMap Adaptor // associative array operator: unimodal V& operator[](const K& k) { TAssociation p; p.key = k; typename C::Iterator i = c.LowerBound(p); if (!i.Valid() || p != *i) { // if not in map or not identical key c.Insert(i, p); } return (*i).value; }

The CMap Adaptor Iterator Insert(const K& k, const V& v) { TAssociation p; Iterator I; I.i = c.LowerBound(p); if (!I.Valid() || p != *I) { // not found if (c.Insert(I.i, p) { return I; } else { return End(); }} (*I).value = v; // overwrite if found return I; } int Insert(Iterator& I, const K& k, const V& v) { TAssociation p(k, v); return c.Insert(I.i, p); }

The CMap Adaptor unsigned int Remove(const K& k) { TAssociation p; p.key = k; return c.Remove(p); } int Remove(Iterator& I) { return c.Remove(I.i); } void Clear() { return c.Clear(); } // size operations unsigned long Size() const { return c.Size(); } int Empty() const { return c.Empty(); }

The CMap Adaptor // locator operations Iterator Includes(const K& k) const { CMapIterator I; TAssociation p; p.key = k; I.i = c.LowerBound(p); if (I.Valid() && (k == (*I).key) { return I; } return End(); } Iterator LowerBound(const K& k) const { … } Iterator UpperBound(const K& k) const { … }

The CMap Adaptor Iterator Begin() const { CMapIterator I; I.i = c.Begin(); return I; } Iterator End() const {…} Iterator rBegin() const {…} Iterator rEnd() const {…} protected: C c; };

The CMapIterator template template class CMapIterator { friend class CMap friend class CMap public: // bidirectional iterator interface protected: typename C::Iterator i; }

The CMultiMap Adaptor template template class CMultiMap { friend class CMapIterator friend class CMapIterator public: typedef K key_type; typedef C container_type; typedef typename C::value_type value_type; typedef CMapIterator Iterator; // proper type CMultiMap() : c() { } CMultiMap(const CMultiMap & MM) : c(MM.c) { } ~CMultiMap() { c.Clear(); } CMultiMap& operator=(const CMultiMap& MM) { … }

The CMultiMap Adaptor // operators Iterator Insert(const K& k, const V& v) { Tassociation p(k, v); Iterator I; I.i = c.Insert(p); return I; } int Insert(Iterator& I, const K& k, const V& v) { TAssociation p(k, v); return c.Insert(I.i, p); } unsigned int Remove(const K& k) { TAssociation p; p.key = k; return c.Remove(p); } int Remove(Iterator& I) { return c.Remove(I.i); } void Clear() { return c.Clear(); }

The CMultiMap Adaptor // size operations unsigned long Size() const { return c.Size(); } int Empty() const { return c.Empty(); } // locator operations Iterator Includes(const K& k) const { Iterator I; TAssociation p; p.key = k; I.i = c.Includes(p); return I; } Iterator LowerBound(const K& k) const { … } Iterator UpperBound(const K& k) const { … }

The CMultiMap Adaptor Iterator Begin() const { CMultiMapIterator I; I.i = c.Begin(); return I; } Iterator End() const {…} Iterator rBegin() const {…} Iterator rEnd() {…} protected: C c; }

The CHashSet Adaptor template template class CHashSet { friend class CHashSetIterator ; public: typedef T value_type; typedef H hash_type; typedef C bucket_type; typedef CHashSetIterator Iterator; // constructor CHashSet(size_t number_of_buckets); ~CHashSet(); // element operations Iterator Insert(const value_type& t); int Insert(Iterator& I, const value_type& t); size_t Remove(const value_type& t); int Remove(Iterator& I); void Clear();

The CHashSet Adaptor // locator operations Iterator Includes(const value_type& t) const; Iterator Begin() const; Iterator End() const; Iterator rBegin() const; Iterator rEnd() const; // size operations int Empty() const; size_t Size() const; protected: size_t numBuckets; TVector bucketVector; H hashObject; private: CHashSet(const CHash &); CHashSet& operator=(const CHashSet&); };

The CHashSetIterator Adaptor template template class CHashSetIterator { friend class CHashSet ; public: // bidirectional iterator public interface protected: const CHashSet *setPtr; typename C::Iterator bucketItr; size_t bucketNum; };