1 STL Map & Multimap Ford & Topp Chapter 11 Josuttis Sections: 6.5 & 6.6 CSE 30331 Lecture 15 – Maps.

Slides:



Advertisements
Similar presentations
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
Advertisements

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.
Beginning C++ Through Game Programming, Second Edition
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.
True or false A variable of type char can hold the value 301. ( F )
1 Associative Containers Gordon College Prof. Brinton.
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
1 Associative Containers Gordon College Prof. Brinton.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
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.
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.
C++ for Engineers and Scientists Third Edition
1 Techniques of Programming CSCI 131 Lecture 29 Search.
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.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structures Using C++ 2E
HASHING Section 12.7 (P ). HASHING - have already seen binary and linear search and discussed when they might be useful (based on complexity)
Containers Overview and Class Vector
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
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)
File I/O ifstreams and ofstreams Sections 11.1 &
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.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Arrays and Vectors Sequential (One-Dimensional) Containers Chapter 12 1.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Adapted from Data Structures with C++ using STL: Ford, Topp CS 362: Queues Dr. Nazli Mollah Overview of Lecture  Introduction  The Queue ADT  The Radix.
Ticket Booth Base Level 3 1. In the completed program, the ticket seller will: Select a venue from a menu of all venues. Select a show from a menu of.
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.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
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.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
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 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Standard Template Library (STL)
Associative Structures
A Sorted, Unique Key Container
Elements are always copied when they are put into a container
Recitation Outline C++ STL associative containers Examples
Chapter 10 1 – Binary Trees Tree Structures (3 slides)
Recitation Outline Hash tables in C++ STL Examples Recursive example
The List Container and Iterators
A dictionary lookup mechanism
Presentation transcript:

1 STL Map & Multimap Ford & Topp Chapter 11 Josuttis Sections: 6.5 & 6.6 CSE Lecture 15 – Maps

2 Brief Intro to Maps Maps are essentially sets of.. Key-value pairs Sorted and accessed by key Multimaps are essentially multisets of … Key-value pairs Sorted and accessed by key

3 Key-Value Data A map stores data as a 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.

4 Maps

5 Map & Set Implementation Usually as a Balanced Binary (Search) Tree

6 Map Ordering The map is ordered using comparison operator less, unless otherwise specified Example: map > myMap; The Comparison must provide a “strict weak ordering” with these properties Antisymetric [if x<y then !(y<x)] Transitive [if x<y and y<z then x<z] Irreflexive [x<x is false] Transitivity of equivalence [if !(x<y) && !(y<x) && !(y<z) && !(z<y) then !(x<z) && !(z<x)] Roughly the same as saying if x==y and y==z then x==z

7 Access & Search Access is by iterator Through the iterator we can change the value but not the key of a particular item To change a key we must erase the item and insert a new one Map has [ ] operator for associative array-like access Set does NOT Search is very efficient -- O(logN)

8 The pair structure Defined in Template struct with two fields (first & second) Constructors and the like … Prototype: pair (T1& val1, T2& val2); Example : pair myPair(“JHS”,51); Function make_pair() is used to construct a nameless pair for passing as parameter, etc template make_pair(T1& val1,T2& val2); Example: make_pair(“JHS”,51):

9 Using pairs Insert function … Takes a key/value pair as parameter Returns an interator/bool pair as value So we can use the returned pair to make decisions typedef map siMap; typedef siMap::value_type kvPair; typedef pair ibPair; siMap myMap; ibPair p; string name = “JHS”; p = myMap.insert(kvPair(name,51)); if (p.second) cout << “ Inserted new pair”; else cout << “already had pair with key and value “ first second;

10 CLASS map Constructors map(); Create an empty map. This is the Default Constructor. map(T *first, T *last); Initialize the map using the range [first, last). CLASS map Operations bool empty() const; Is the map empty? int size() const; Return the number of elements in the map.

11 CLASS map Operations int count(const T& key) const; Search for key in the map and return 1 if it is in the map and 0 otherwise. iterator find(const T& key); Search for key in the map and return an iterator pointing at it, or end() if it is not found. Const_iterator find(const T& key) const; Constant version.

12 CLASS map Operations pair insert(const T& item); If key (item.first) is not in the map, insert and return a pair whose first element is an iterator pointing to the new element and whose second element is true. Otherwise, return a pair whose first element is an iterator pointing at the existing element and whose second element is false. Postcondition: The set size increases by 1 if key is not in the map. int erase(const T& key); If key is in the map, erase all items it is part of and return number of removals; otherwise, return 0. Postcondition: The set size decreases by number of removals if key is in the map.

13 CLASS map Operations void erase(iterator pos); Erase the item pointed to by pos. Preconditions: The map is not empty, and pos points to a valid map element. Postcondition: The set size decreases by 1. void erase(iterator first, iterator last); Erase the elements in the range [first, last). Precondition: The map is not empty. Postcondition: The map size decreases by the number of elements in the range.

14 CLASS map Operations iterator begin(); Return an iterator pointing at the first member in the map. const_iterator begin(const); Constant version of begin(). iterator end(); Return an iterator pointing just past the last member in the map. const_iterator end() const; Constant version of end().

15 Associative Arrays Map has [ ] operator to give array-like access M[key] returns a reference to the value of the item with given key If no item is in map with key, then a new item is inserted in the map with the specific key and a default value (from the default constructor for its type) M[“bob”]=8.3 Either changes value of exiting item to 8.3 Or creates new item (“bob”,0.0) and then sets value to 8.3 in second stage

16 Example program Concordance (prg11_5.cpp in Ford&Topp) Uses a map of sets Map > concordMap; Each entry corresponds to a word and the associated “value” is a set of line numbers indicating lines on which the word is found Reads a text file character by character While there is another word Insert word/line_number pair into map If on new line increment line counter

17 Concordance // File: prg11_5.cpp // prompt user for name of a text file containing identifiers, // where an identifier begins with a letter ('A'..'Z', 'a'..'z') // followed by 0 or more letters or digits ('0'..'9'). function // concordance() takes a file name as an argument and uses a map // with key string and value set to determine each identifier, // the number of lines on which it occurs, and the line numbers on // which it appears. concordance() calls writeConcordance() to // display the results in the format // identifiern: line# line# line#... #include #include // for functions isalpha() and isdigit() #include "d_util.h“ // for writeContainer(iter1,iter2) using namespace std;

18 Concordance // input filename and output a concordance void concordance(const string& filename); // output the identifier, the number of lines containing the // identifier, and the list of lines having the identifier void writeConcordance(const map >& concordance); int main() { string filename; // get the file name cout << "Enter the file name: "; cin >> filename; cout << endl; // create the concordance concordance(filename); return 0; }

19 Concordance void concordance(const string& filename) { // declare the concordance map map > concordanceMap; // objects to create identifiers and maintain line numbers char ch; string identifier = ""; bool beginIdentifier = true; int lineNumber = 1; // file objects ifstream fin; // open the input file fin.open(filename.c_str()); if (!fin) { cerr << "Cannot open '" << filename << "'" << endl; exit(1); }

20 Concordance // read the file character by character to determine each // identifier and update line numbers while(true) { fin.get(ch); if (!fin) break; // check for a letter that begins an identifier if (isalpha(ch) && beginIdentifier) { // add char to identifier and continue scan identifier += ch; beginIdentifier = false; } // check if subsequent letter or digit in an identifier else if ((isalpha(ch) || isdigit(ch)) && !beginIdentifier) identifier += ch;

21 Concordance else // not part of an identifier { // if we have just finished with an identifier, use the index // operator to access a map entry with identifier as the key. if not // in the map, the operator adds an entry with an empty set as the // value component. if in the map, the operator accesses the set // component. in either case, insert the current line number if (!beginIdentifier && identifier != "") concordanceMap[identifier].insert(lineNumber); if (ch == '\n') lineNumber++; // increment lineNumber when ch == '\n' // reset objects preparing for next identifier beginIdentifier = true; identifier = ""; } // output the concordance writeConcordance(concordanceMap); }

22 Concordance void writeConcordance(const map >& concordance) { map >::const_iterator iter = concordance.begin(); int i; while (iter != concordance.end()) { cout << (*iter).first; // output key // pad output to 12 characters using blanks if ((*iter).first.length() < 12) for (i=0;i < 12 - (*iter).first.length();i++) cout << ' '; // output number of lines and specific line numbers where id occurs cout << setw(4) << (*iter).second.size() << ": "; writeContainer((*iter).second.begin(),(*iter).second.end()); cout << endl; iter++; } cout << endl; }

23 Concordance File: "concord.txt" int m, n; double a = 3, b = 2, hypotenuse; cin << m; if (n <= 5) n = 2*m; else n = m * m; cout << n << endl; hypotenuse = sqrt(a*a + b*b); cout << hypotenuse << endl; Run: Enter the file name: concord.txt a 2: 2 12 b 2: 2 12 cin 1: 4 cout 2: double 1: 2 else 1: 7 endl 2: hypotenuse 3: if 1: 5 int 1: 1 m 4: n 5: sqrt 1: 12

24 Next Assignment Web Crawler (local) Read set of connected (local) HTML pages Build a vector of filenames Build a map of > pairs Each string is a map key and is a word from a page Each set contains the id’s of all web pages containing the word The web page id is the position of its name in the vector Case is not meaningful (word = WORD = WoRd) Each page should be processed only once All tags are ignored, except for those leading to other pages Format of final output IS important

25 Summary Sets and maps are associative containers Both store and retrieve data by value rather by position. A set is a collection of keys, where each key is unique. In a multiset each key may appear multiple times. A map is a collection of key-value pairs, where each key is unique. In a multimap, each key may be part of multiple key-value pairs.

26 Summary Implementation Binary search tree ideal, since it is an ordered associative data structure and its iterators traverse its values in order. Map Often called an associative array because applying the index operator with the key as its argument accesses the associated value.

27 Summary Multiset Like a set, except a key can occur more than once. The member function count() and equal_range() deal with duplicate values. Multimap Like a map, except a key can occur more than once, each time with a (potentially) different value. The member function count() and equal_range() deal with duplicate values.