120 likes | 305 Views
Map and Set ADTs. Joe Meehean. Conceptual Pictures. List of names Set of names Map names as keys phone #’ s as values. [Phil, Will, Bill]. Phil. Phil. Will. Will. Bill. Bill. Phil: 555-5699. Phil. Will: 555-0111. Will. Bill. Bill: 555-9864. Sets.
E N D
Map and Set ADTs Joe Meehean
Conceptual Pictures • List of names • Set of names • Map • names as keys • phone #’s as values [Phil, Will, Bill] Phil Phil Will Will Bill Bill Phil: 555-5699 Phil Will: 555-0111 Will Bill Bill: 555-9864
Sets • Unorded collection of itemswithout duplicates • List implementation • add => O(N): check for uniqueness • contains => O(N) • bad idea • Balanced tree implementation • much better (we’ll see more about this later)
C++ STL Sets set<Key, Compare, Alloc> Key is the data type being stored Compare is a comparator Ignore Alloc (almost never needed)
C++ STL Set Methods • pair<iterator,bool> insert(const T &key) • inserts the key • bool is true if key not already in set • size_type erase(const T &key) • removes the item from the set • iterator find(const T &key) • returns iterator to key • iterator begin(), end()
Sets vs Lists • Both store collections of objects • Lists are ordered, sets are not • items have a position in a list • positions are meaningless in sets • Duplicates • list can contain duplicates • sets, no way
Sets vs Lists • Implementation • lists: array or linked list • sets are balanced trees or hash tables • Some operations are faster in a set • remove • contains • Use a set when… • don’t have/want duplicates • position does not matter • need fast contains and remove
Maps • An unorded collection of unique keys with associated values • no duplicate keys allowed • Generalization of an array • arrays can only be indexed by ordinal data types • maps can be indexed with any comparable type • What is ordinal data types? • type with 1-to-1 mapping integers
Map Terminology • Maps • verb: a key is associated with stated value • e.g., B maps to 2 • symbol: B => 2 • Mapping • noun: key-value pair • symbol: B => 2 • Associative array, dictionary • other words for map (n)
C++ STL Maps • map<Key, Data, Compare, Alloc> • Key is the data type of the key • Data is the data type of the value • Compare is a comparison functor • Ignore Alloc (almost never needed)
C++ STL Maps Methods • Map methods • Overloads the [ ] operator • Insert • map[“Bill”] = 27 • Access • cout << map[“Bill”] << endl; • Erase • map.erase(“Bill”)