1 Associative Containers Gordon College Prof. Brinton.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
1 STL Map & Multimap Ford & Topp Chapter 11 Josuttis Sections: 6.5 & 6.6 CSE Lecture 15 – Maps.
Multimaps. Resources -- web For each new class, browse its methods These sites are richly linked, and contain indexes, examples, documents and other resources.
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,
Week 5 - Associative Containers: sets and maps. 2 2 Main Index Main Index Content s Content s Container Types Sequence Containers Adapter Containers Associative.
1 Associative Containers Gordon College Prof. Brinton.
1 Standard Containers: Lists Gordon College Resource:
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
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.
CSE 332: C++ Associative Containers II Associative Containers’ Associated Types Associative containers declare additional types –A key_type gives the type.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data Structures Using C++ 2E
Containers Overview and Class Vector
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
STL OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 1 The Standard Template Library STL Components Sequential.
STL-Associative Containers. Associative Containers Sequence containers : "This is item 0, this is item 1, this is item 2…“ Associative containers : –
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Dictionaries Collection of pairs.  (key, element)  Pairs have different keys  E.g. a pair contains two components, student id and name (1234, Nan)
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
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.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
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.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
1 Joe Meehean.  List of names  Set of names  Map names as keys phone #’s as values Phil Bill Will Phil Bill Will Phil Bill Will Phil: Bill:
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
Lecture 7 : Intro. to STL (Standard Template Library)
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 6. Dictionaries(3): Binary Search Trees.
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.
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.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
@ Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 17 B-Trees and the Set Class Instructor: Zhigang Zhu Department of Computer Science.
STL Associative Containers navigating by key. Pair Class aggregates values of two, possibly different, types used in associative containers defined in.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
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.
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.
Object-Oriented Programming (OOP) Lecture No. 41
Introduction to olympic programming
CSCE 210 Data Structures and Algorithms
CSC212 Data Structure - Section AB
Standard Template Library (STL)
What remains Topics Assignments Final exam
Chapter 9 – Sets and Maps 9.1 Associative Container
Associative Structures
A Sorted, Unique Key Container
Lists - I The List ADT.
Lists - I The List ADT.
Copyright © – Curt Hill STL List Details Copyright © – Curt Hill.
Iterators and STL Containers
An Introduction to STL.
Recitation Outline Hash tables in C++ STL Examples Recursive example
Chapter 9 – Sets and Maps 9.1 Associative Container
A dictionary lookup mechanism
Presentation transcript:

1 Associative Containers Gordon College Prof. Brinton

2 STL - Assoc. Containers Set –The key is the data set intSet; set keyword; set timeSet; To support the STL container - set; the programmer must overload the == operator and < operator by comparing the key field and giving a Boolean result.

3 STL - Assoc. Containers Map –Stores entries as key-value pair. –In a pair, the first component is the key; the second is the value. Each component may have a different data type. map studentFile; studentFile[ ] = new studentFile; studentFile[ ].addToBalance(112);

4 Set and Map Both containers do not allow duplicate keys. Multiset and multimap (also STL containers) allow duplicate keys)

5 STL sets and maps

6 STL Set include Constructors: set(); default - empty set set(T *first, T *last);use pointers or iterators Examples: set first; // empty set of ints int myints[]= {10,20,30,40,50}; set second (myints,myints+5); // pointers set third (second); // a copy of second set fourth (second.begin(), second.end()); // iterators into second

7 STL Set include Operations: bool empty() const; void clear(); int size() const; int count(const T& key) const;//return either 1 or 0 iterator find(const T& key); const_iterator find(const T& key) const; // returns either an iterator or end() NOTE: STL Associative Containers iterators do access the elements in the defined order.

8 STL Set include Operations: pair insert(const T& key); // this return a pair object Example: string t[]={"this","is","a","test"}; set s(t,t+4); pair ::iterator,bool> result = s.insert("OK"); (result.second)?cout << "TRUE":cout << "FALSE"; result = s.insert("OK"); (result.second)?cout << "TRUE":cout << "FALSE"; Result: TRUEFALSE

9 STL Set include Operations: void erase ( iterator position ); void erase ( iterator first, iterator last ); size_type erase ( const key_type& x );//returns either 1 or 0 void swap ( set & st ); Obtaining the bounds: pair equal_range ( const key_type& x ) const; iterator lower_bound ( const key_type& x ) const; //iterator of first value not < x iterator upper_bound ( const key_type& x ) const; //iterator of first value > x

10 STL Set include Iterators: iterator begin(); const_iterator begin(const); iterator end(); const_iterator end(const);

11 Set operators Union setC = setA + setB; setC = IntersectionA*B setC = setA * setB; setC = Difference setC = setA - setB; setC =

12 Map include Operations are like set’s operations –swap –begin –end –size –empty –operator[]//unlike set –find –erase See the following examples

13 #include using namespace std; int main() { map Employees; Employees[5234] = "Mike C."; Employees[3374] = "Charlie M."; Employees[1923] = "David D."; Employees[7582] = "John A."; Employees[5328] = "Peter Q."; cout << "Employees[3374]=" << Employees[3374] << endl << endl; cout << "Map size: " << Employees.size() << endl; for( map ::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }

14 #include using namespace std; int main() { map Employees; Employees[5234] = "Mike C."; Employees[3374] = "Charlie M."; Employees[1923] = "David D."; Employees[7582] = "John A."; Employees[5328] = "Peter Q."; cout << "Employees[3374]=" << Employees[3374] << endl << endl; cout << "Map size: " << Employees.size() << endl; for( map ::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; } Employees[3374]=Charlie M. Map size: : David D. 3374: Charlie M. 5234: Mike C. 5328: Peter Q. 7582: John A.

15 #include using namespace std; int main() { map Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair ("David D.",1923)); Employees.insert(map ::value_type("John A.",7582)); Employees.insert(make_pair("Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl; for( map ::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }

16 #include using namespace std; int main() { map Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair ("David D.",1923)); Employees.insert(map ::value_type("John A.",7582)); Employees.insert(make_pair("Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl; for( map ::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; } Map size: 5 Charlie M.: 3374 David D.: 1923 John A.: 7582 Mike C.: 5234 Peter Q.: 5328

17 struct cmp_str { bool operator()(char const *a, char const *b) { return strcmp(a, b) < 0; } }; int main() { map Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair ("David D.",1923)); Employees.insert(map ::value_type("John A.",7582)); Employees.insert(make_pair((char *)"Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl; for( map ::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }

18 struct cmp_str { bool operator()(char const *a, char const *b) { return strcmp(a, b) < 0; } }; int main() { map Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair ("David D.",1923)); Employees.insert(map ::value_type("John A.",7582)); Employees.insert(make_pair((char *)"Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl; for( map ::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; } Map size: 5 Charlie M.: 3374 David D.: 1923 John A.: 7582 Mike C.: 5234 Peter Q.: 5328 Could this be ordered differently?

19 Map details Associative Arrays M[“Computer Science”] = 20; Keys are unique therefore: M[“Computer Science”] = 26; replaces the value in the tree for CS.

20 Map details Creating a map: #include int main() { map A; …

21 Map Details [ ] operator Steps 1.Search the for map for key 2.If key found, return a reference to the value object associated with key. 3.If key not found, create a new object of type value associated with key, and return a reference to that.

22 Map Details [ ] operator int salary = Employee[“Jack Smith”]; Caution: this will create a new tree entry if it doesn’t exist and assign 0 to variable salary

23 Map Details [ ] operator Better technique: if (( itr = Employee.find(“Jack Smith”)) == Employee.end()) cout << “ the employee does not exist.” << endl; Else cout second << endl;

24 Map Details Pair Class 1. Contains two public members, first and second 2. Store key/value association itr->first itr->second

25 Map Details Pair Class Easiest way to construct pair: pair a; a = make_pair(string(“Jack Smith”), int(100000));

26 Map Details Element requirements: Each key and value must be assignable (an assignment operator which performs a “deep copy” Deep copy target of the assignment should be equal but independent of the source a = b; the value of a should match b - however if you change a it should not affect b (and vice versa) Note: if we talking about a linked list then a shallow copy would have two pointers pointing to the same list.

27 Map Details Element requirements: Also each key should adhere to “weak ordering”: 1. A<A is false 2. Equality can be determined with (!(A<B) && !(B<A)) Note: only using the less than operator 3. If A<B and B<C then A<C must be true int, char, double, etc. (built-in types) are strict weak ordered

28 Map Details Element requirements: value type used must have a defined default constructor. map The built in types have a type of default constructor: map

29 Map Details OperationDescriptionTime Complexity swap Swaps elements with another map. This operation is performed in constant time. Ex: map1.swap(map2); O(1) begin Returns an iterator to the first pair in the map. Ex: itr = map1.begin(); O(1) end Returns an iterator just beyond the end of the map. O(1)

30 Map Details OperationDescriptionTime Complexity size Returns the number of elements contained by the map. You should use empty() to test whether or not size equals 0, because empty() is faster. cout << map1.size(); O(n) empty Returns true if the map contains zero elements. O(1) Operator [ ]Accepts a key and returns a reference to the object associated with key. Note that this operator always creates an element associated with key if it does not exist. O(log n)

31 Map Details OperationDescriptionTime Complexity find Accepts a key and returns an iterator to the pair element if found. If the key is not found in the map, this method returns end(). if ( (itr = map1.find("Bob")) == map1.end()) cerr << "Bob was not found in the map." << endl; else cout << "Bob was found in the map." << endl; O(log n)

32 Map Details OperationDescriptionTime Complexity erase There are three overloaded forms of this method. The first accepts a single iterator, and removes the element implied by the iterator from the map. The map should be non-empty. O(1). map1.erase(map1.begin()); // remove the first element O(1)

33 Map Details OperationDescriptionTime Complexity erase There are three overloaded forms of this method. The second accepts two iterators, that specify a range of values within the map to be removed. The time complexity is logarithmic plus linear time for the length of the sequence being removed. The two iterators must be valid iterators within the sequence contained by the map. Formally, the range of values [starting, ending) are removed. At worst, this is an O(n) operation. Ex: map1.erase(map1.begin(), map1.end()); // erase the entire map O(n)

34 Map Details OperationDescriptionTime Complexity erase There are three overloaded forms of this method. The last accepts an object of the key type, and removes all occurrences of the key from map. Note that since map elements all have unique keys, this will erase at most 1 element. O(log n). Ex: map1.erase(string("Bob")); // removes all occurrences of "Bob" O(log n)

35 Multimap/Multiset beginend rbeginrend clearempty count equal_rangelower_bound upper_bound insert erase find max_size operator= size swap

36 Multimap/Multiset Details OperationDescription constructorcreates an empty multiset multiset S sizereturns the number of elements S.size() insertS.insert( const T& ) : adds an item to the set. If the item is already present, there will be multiple copies in the multiset/multimap S.insert(6);

37 Multimap/Multiset Details OperationDescription countS.count( const T& t ) : returns the number of times that the item t is found in the set. This will be 0 if the item is not found eraseS.erase( const T& t ) : removes the all items equal to t from the multiset. eraseS.erase( multiset ::iterator i ) : removes the item pointed to by i. S.erase( v ); // ALL: removes all of items == v from the multiset S.erase( S.find( v ) ); // ONE: removes the first item == v from the multiset

38 Multimap/Multiset Details OperationDescription reverse reverse( iterator begin, iterator end ) : reverses the order of the items: find S.find( const T& t ) : returns an iterator that points to the first item == t, or S.end() if the item could not be found.

39 Multimap/Multiset Details OperationDescription equal_rangeS.equal_range(*iter) - returns a pair of iterators such that all occurrences of the item are in the iterator range pair ::iterator, multiset ::iterator > p; p = S.equal_range(5);

40 Multimap/Multiset Details equal_range multiset ::iterator it; pair ::iterator,multiset ::iterator> ret; int myints[]= {77,30,16,2,30,30}; multiset mymultiset (myints, myints+6); // ret = mymultiset.equal_range(30); for (it=ret.first; it!=ret.second; ++it) ++(*it); //

41 Multimap/Multiset Details How is multiset implemented? Multiset: BST - with integer value representing each occurrence of the element insert {find - if not present create node else increment count} erase {remove node and report back count} (2) (1) (5) (2) (3) (1) HOW WOULD THESE BE HANDLED? clearempty count find size

42 Multimap/Multiset Details How is multimap implemented? Multimap: BST - with list or map as the node’s payload insert {find - if not present create node else add value to list/set} erase {remove node and report back count} HOW WOULD THESE BE HANDLED? clearempty count find size There is not guarantee as to order of duplicates (“Tom” -> “Jack” -> “Joe”) (“Tom”) (“Jack” -> “Joe”) (“Jack”) (“Jack” -> “Joe”) (“Emma”)