270 likes | 503 Views
STL Associative Containers . CSCI 3110. STL Containers. Sequence Containers – store sequences of values vector deque list Associative Containers – use “keys” to access data rather than position (Account #, ID, SSN, …) set multiset map multimap. Containers continued.
E N D
STL Associative Containers CSCI 3110
STL Containers • Sequence Containers – store sequences of values • vector • deque • list • Associative Containers – use “keys” to access data rather than position (Account #, ID, SSN, …) • set • multiset • map • multimap
Containers continued • Container Adapters – specialized interfaces to general containers • stack • queue • priority_queue
Associative Containers • Stores elements based on a key • Key can consist of one or more attributes to uniquely identify each element (we will assume only one attribute). • Example: Department of Motor Vehicles (DMV) uses license-plate # to identify a vehicle. • Similar to vector & list – it is another storage structure with operations to access & modify elements. • Main difference is that associative-container uses the key rather than an index (vector) or linear search (list) to retrieve an element.
Associative-Container : set • Stores a set of values (i.e., “keys”) • Values are unique (stored only once) • Implemented as a balanced binary search tree (red-black tree) • #include <set> • set<string> s; • Fast insert and delete • insert, erase • Fast search • find • Other operations • size, empty, clear, . . . “if” “operator” “while” “class” “template”
Associative Containers: multiset • Stores a set of values (i.e., “keys”) • Like set, but values need not be unique • Implemented as a balanced binary search tree (red-black tree) • #include <set> • multiset<string> ms; • Fast insert and delete • insert, erase • Fast search • find • Other operations • size, empty, clear, . . .
Associative Containers: map • Stores a set of (key, value) pairs • Each key has one value • Implemented as a balanced binary search tree (red-black tree) #include <map> //define a map with //keys of type string //and values of int map<string, int> m; • Fast insert and delete m[“fred”] = 99; insert, erase “fred” | 99 “sue” | 86 “james” | 52
Associative Containers: map • Fast search • int x = m[“fred”]; • find • Other operations • size, empty, clear, . . .
Associative Containers: sorting • STL associative containers are implemented internally using a red-black tree which is a BST • Key classes stored in associative containers must implement bool operator< (T other) • If they don’t, you can alternately pass a comparator class to the template that it should use to order elements • A comparator class overrides bool operator() (T a, T b);
Associative Containers:comparator example set<Employee *> employees; //BST sorts based on pointers //(probably not what you want) class EmployeeComparator { public: bool operator() (const Employee* a, const Employee* b) { return (a->getID() < b->getID()); } }; //create a set that sorts based on employee IDs set<Employee*, EmployeeComparator> employees;
Writing classes that work with the STL • Classes that will be stored in STL containers should explicitly define the following: • Default constructor • Copy constructor • Destructor • operator = • operator== • operator< • Not all of these are always necessary, but it might be easier to define them than to figure out which ones you actually need • Many STL programming errors can be traced to omitting or improperly defining these methods
STL Maps: Constructors Copy constructor: • Copy constructor: map<char,int> m; map<char,int> m2(m);
STL Maps: Data Storage • An STL map is implemented as a tree-structure, where each node holds a “pair” • Most important to know when retrieving data from the table • Some functions return the pair, not just the value • A pair has two fields, first (holding the key) and second (holding the value)
STL Map: Data Storage • If you have a pair object, you can use the following code to print the key and value: cout << myPairObject.first << “ “ << myPairObject.second; • If you have a pointer to the pair object, use the arrow operator instead cout << myPairObject->first << “ “ << myPairObject->second;
STL Maps: Data Storage • Tree structure • logarithmic time inserts, finds, deletes
STL Map: Available Methods void clear() remove all elements bool empty() returns true if empty, false otherwise size_type max_size() returns max number of elements map can hold (usually an integer returned) [capacity] size_type size() return the number of elements currently in the map (usually an integer returned) [actual size]
STL Map: Available Methods iterator begin() returns an iterator to the first element in the map (the first when sorted, due to storage mechanism) iterator end() returns an iterator to the last element in the map (the last when sorted) reverse_iteratorrbegin() returns a reverse iterator to the end of the map reverse_iterator rend() returns a reverse iterator to the start of the map
STL Map: Available Methods pair<iterator,bool> insert(const value_type &val) Insert val into the map, if it’s not already there. Return pair<iterator,true> if successful, pair<iterator,false> if fails. iterator insert(iterator I, const value_type &val) Insert val into the map, after the value specified by i. Iterator to inserted element is returned. template <class InIter> void insert(InIter start, InIter end) Insert a range of elements
STL Map: Available Methods void erase (iterator i) Remove the element pointed to by i. size_type erase(const key_type & k) Remove from the map elements that have keys with the value k. void erase(iterator start, iterator end) Remove the elements in the range start to end
STL Map: Available Methods iterator find(const key_type &k) Returns an iterator to the specified key. If the key is not found, an iterator to the end of the map is returned. size_type count(const key_type &k) const Returns the number of times a key k occurs in the map (0 or 1) reference operator[](const key_type &k) Returns a reference to the value associated with the key k. If the key is not found in the map, the key and a default constructed instance of the value type is inserted in the amp.
STL Map: Available Methods iterator lower_bound(const key_type &k) Returns an iterator to the first element in the map with a key >= k iterator upper_bound(const key_type &k) const Returns an iterator to the first element in the map with a key strictly > k pair<iterator, iterator> equal_range(const key_type &k) Returns a pair of iterators that point to the upper bound and the lower bound in the map for the specified key
STL Map: Example Map between Characters and ASCII representations Map between characters and ASCII representations
STL Map: Example Same program, exploiting []
STL Map: Example Print all entries in map in forward and reverse order
STL Map: Example Storing objects, requiring an overload of the < operator for the key type