This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: CSCI-1200 Data Structures Fall 2010 Lecture 15 Associative Containers (Maps), Part 2 Announcenments Tuesdays lecture (Nov 2nd) will be shortened (2:00-2:45) to allow students to attend the Craig Mundie lecture, @3pm in the EMPAC Concert Hall: http://www.rpi.edu/news/events/mundie/ Review of Lecture 14 Maps are associations between keys and values. Maps have fast insert, access and remove operations: O(log n), well learn why next week when we study the implementation! Maps store pairs; map iterators refer to these pairs. The primary map member functions we discussed are operator , find , insert , and erase . The choice between maps, vectors and lists is based on naturalness, ease of programming, and efficiency of the resulting program. Todays Class Maps, Part 2 Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear. Maps whose keys are class objects, example: maintaining student records. Lists vs. Graphs vs. Trees Intro to Binary Trees, Binary Search Trees, & Balanced Trees 15.1 More Complicated Values map<string, vector<int> > m 15 5 "hello" first second p q Lets look at the example: map<string, vector<int> > m; map<string, vector<int> >::iterator p; Note that the space between the > > is required . Otherwise, >> is treated as an operator. Heres the syntax for entering the number 5 in the vector associated with the string "hello" : m[string("hello")].push_back(5); Heres the syntax for accessing the size of the vector stored in the map pair referred to by map iterator p: p = m.find(string("hello")); p->second.size() Now, if you want to access (and change) the i th entry in this vector you can either using subscripting: (p->second)[i] = 15; (the parentheses are needed because of precedence) or you can use vector iterators: vector<int>::iterator q = p->second.begin() + i; *q = 15; Both of these, of course, assume that at least i+1 integers have been stored in the vector (either through the use of push back or through construction of the vector). We can figure out the correct syntax for all of these by drawing pictures to visualize the contents of the map and the pairs stored in the map. We will do this during lecture, and you should do so all the time in practice. 15.2 Exercise Write code to count the odd numbers stored in the map map<string, vector<int> > m; This will require testing all contents of each vector in the map. Try writing the code using subscripting on the vectors and then again using vector iterators....
View Full Document
- Fall '08
- Data Structures