Chapter 9 – Sets and Maps 9.1 Associative Container

Slides:



Advertisements
Similar presentations
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Advertisements

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.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
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.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Lecture Objectives To understand the Java Map and Set interfaces and how to use them To be introduced to the implementation of Map s and Set s To see how.
Data Structures Using C++ 2E
Containers Overview and Class Vector
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Generic Programming Using the C++ Standard Template Library.
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.
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
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.
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.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
Motivation for Generic Programming in C++
CS212: Object Oriented Analysis and Design
Sets and Maps Chapter 9.
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
C++ Standard Library.
Standard Template Library (STL)
Basic Data Structures.
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
What remains Topics Assignments Final exam
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 9 – Sets and Maps 9.1 Associative Container
Basic Data Structures.
18 – Sequential Containers
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Chapter 8 – Binary Search Tree
Associative Structures
A Sorted, Unique Key Container
Lists - I The List ADT.
Lists - I The List ADT.
Pointers & Dynamic Data Structures
Iterators and STL Containers
Sets and Maps Chapter 9.
STL (Standard Template Library)
Standard Template Library
C++ Programming: chapter 10 – STL
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
SPL – PS1 Introduction to C++.
A dictionary lookup mechanism
9.2 Maps and Multimaps 9.3 Hash Tables 9.2, pgs
Standard Template Library
Presentation transcript:

Chapter 9 – Sets and Maps 9.1 Associative Container The Set Abstraction The Set Functions The multiset Standard Library Class pair Chapter 9 – Sets and Maps

Tip #30: Solving Compiler Errors Heaps / Priority Queues When you get any compiler error in MS Visual Studio, then in the Error List Panel, you will see ERROR CODE along corresponding error. Enter that ERROR Code with keyword "MSDN" in GOOGLE, and you will get a link on MSDN. In that link, you will find every detail on that error and information on how to fix it. For other compilers, you can often search for the name of the compiler followed by the error message.

Sets and Maps Chapter 9

Chapter Objectives Associative Containers To understand the C++ set and map containers and how to use them. To learn about hash coding and its use to facilitate efficient search and retrieval. To study two forms of hash tables — open addressing and chaining — and to understand their relative benefits and performance trade-offs. To learn how to implement both hash table forms. To be introduced to the implementation of maps and sets. To see how two earlier applications can be implemented more easily using maps objects for data storage.

Introduction Sequential containers: Associative Containers Sequential containers: Searching for a particular value in a sequential container is generally O(n). (An exception is a binary search for a sorted object, which is O(log n).) Sequential containers include vector, list, and deque. We consider another part of the container framework, the associative containers: Are not indexed, but must have unique key. Do not reveal the order of insertion of items. Elements follow a strict weak ordering using binary relation <. Enable efficient search and retrieval of information. Allow removal of elements without moving other elements around. Associative containers include the set, multiset, map, and multimap.

9.1, pgs. 512-520 9.1 Associative Container Requirements The Set Abstraction The Set Functions The multiset Standard Library Class pair 9.1, pgs. 512-520

Associative Container Requirements Associative Containers Associative containers refer to a group of class templates in the STL library that implement ordered and unordered associative arrays. Being STL templates, associate containers can be used to store arbitrary elements, such as integers or custom classes. Associative container characteristics: Key uniqueness: in map and set each key must be unique. multimap and multiset do not have this restriction. Element composition: in map and multimap each element is composed from a key and a mapped value. In set and multiset each element is key; there are no mapped values. Element ordering: elements follow a strict weak ordering accessible thru iterators.

Associative Containers A set is an associative container that contains no duplicate elements. A multiset is a set that may contain duplicate elements. A map is a collection of unique name-value pairs. A multimap is a map that may contain duplicate keys.

The set Abstraction Operations on sets include: Testing for membership Associative Containers Operations on sets include: Testing for membership Example: Is {5} in {1, 3, 5, 7} ? true Adding elements Example: Insert {10} in {1, 3, 5, 7} equals {1, 3, 5, 7, 10} Removing elements Example: Remove {5} from {1, 3, 5, 7, 10} equals {1, 3, 7, 10} Size of membership Example: How many in {1, 3, 5, 7} ? 4 The union of two sets A, B is a set whose elements belong either to A or B or to both A and B. Example: {1, 3, 5, 7} ∪ {2, 3, 4, 5} is {1, 2, 3, 4, 5, 7} The intersection of sets A, B is the set whose elements belong to both A and B. Example: {1, 3, 5, 7} ∩ {2, 3, 4, 5} is {3, 5} The difference of sets A, B is the set whose elements belong to A but not to B. Examples: {1, 3, 5, 7} – {2, 3, 4, 5} is {1,7} Set A is a subset of set B if every element of set A is also an element of set B. Example: {1, 3, 5, 7} ⊂ {1, 2, 3, 4, 5, 7} is true

The set Template Class Associative Containers The set and multiset are implementations of the Set ADT. The set is a template class that takes the following template parameters: template< class Key_Type, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > class set; where Key_Type: The type of the item contained in the set. Compare: A function class (functor) that determines the ordering of the keys. (Default is the less-than operator.) Allocator: The container uses an allocator object to dynamically handle its storage needs. (We will use the library supplied default.) Although not a requirement, C++ stores items in a set as ordered by their Compare function. If you iterate through a set, you get a sorted list of the contents.

The set Default Parameters Associative Containers class Compare The elements of a set are ordered using the compare operator< or a user supplied class compare functor. Two elements, a and b are considered equivalent if (!(a < b) && !(b < a)) or (!comp(a, b) && !comp(b, a)). The set elements are always ordered according to this same criterion (operator< or comp). class Allocator List, set, and map containers change size during the execution of a program using some form of dynamic memory allocation. Allocators handle all the requests for allocation and deallocation of memory for a given container. Programs with frequent allocations of small amounts of memory may benefit from specialized user defined allocators, both in terms of running time and memory footprint.

The set Functions Associative Containers

<algorithm> Associative Containers The header <algorithm> defines a collection of functions especially designed to be used on ranges of elements. A range is any sequence of objects that can be accessed through iterators or pointers, such as an array or an instance of some of the STL containers. The elements are compared using operator< and considered equivalent if (!(a < b) && !(b < a)) or (!comp(a, b) && !comp(b, a)). The elements in the ranges are ordered according to this same criterion (operator< or comp). Function Behavior set_union Union of two sorted ranges. set_difference Difference of two sorted ranges. set_intersection Intersection of two sorted ranges.

Standard Library Class inserter Associative Containers The iterator adaptor inserter constructs an insert iterator used to insert new elements into container in successive locations starting at the iterator position iter. Elements are inserted into a container rather than overwriting existing elements in the container. inserter takes two arguments: a container an iterator within the container Each insertion appends the next element to the current end of the container. template <class Container, class Iterator> insert_iterator<Container> inserter(Container& container, Iterator iter);

The set Union Function Associative Containers Forms the set union of the elements in the sorted sequence first1...last1 and the elements in the sorted sequence first2...last2. result is the output iterator to the initial position of the range where the resulting union set sequence is stored. The elements are compared using operator<. An iterator to the end of result is returned. template <class IIter1, class IIter2, class OIter> OIter set_union (IIter1 first1, IIter1 last1, IIter2 first2, IIter2 last2, OIter result); Example1: set<string> set1; set<string> set2; set<string> set_u; string data1[] = { "Apples", "Oranges", "Pineapples" }; string data2[] = { "Peaches", "Apples", "Grapes" }; set1.insert(data1, data1 + 3); set2.insert(data2, data2 + 3); set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_u, set_u.begin())); cout << "set1 + set2 is " << set_u << endl; set1 + set2 is {Apples, Grapes, Oranges, Peaches, Pineapples}

Difference/Intersection Functions Associative Containers Example2: set<string> set1; set<string> set2; set<string> set_d; string data1[] = { "Apples", "Oranges", "Pineapples" }; string data2[] = { "Peaches", "Apples", "Grapes" }; set1.insert(data1, data1 + 3); set2.insert(data2, data2 + 3); set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_d, set_d.begin())); cout << "set1 - set2 is " << set_d << endl; set1 - set2 is {Oranges, Pineapples} Example3: set<string> set1; set<string> set2; set<string> set_i; string data1[] = { "Apples", "Oranges", "Pineapples" }; string data2[] = { "Peaches", "Apples", "Grapes" }; set1.insert(data1, data1 + 3); set2.insert(data2, data2 + 3); set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_i, set_i.begin())); cout << "set1 * set2 is " << set_i << endl; set1 * set2 is {Apples}

Sets set1 + set2 is set1 - set2 is set1 * set2 is #include <iostream> #include <string> #include "set_functions.h" using namespace std; int main() { set<string> set1; set<string> set2; set<string> set_u; set<string> set_d; set<string> set_i; string data1[] = { "JA", "BB", "ZA", "QA", "DC", "RJ", "MJ", "AD", "AC", "RA" }; string data2[] = { "GQ", "AC", "AD" }; set1.insert(data1, data1 + 10); set2.insert(data2, data2 + 3); set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_u, set_u.begin())); cout << "set1 + set2 is " << set_u << endl; set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_d, set_d.begin())); cout << "set1 - set2 is " << set_d << endl; set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_i, set_i.begin())); cout << "set1 * set2 is " << set_i << endl; return 0; } Sets /** Insertion (<<) operator. */ template<typename T> ostream& operator<<(ostream& out, const set<T>& a_set) { string prefix = "{"; for (set<T>::const_iterator iter = a_set.begin(); iter != a_set.end(); ++iter) out << prefix << *iter; prefix = ", "; } return out << "}"; set1 + set2 is set1 - set2 is set1 * set2 is {AC, AD, BB, DC, GQ, JA, MJ, QA, RA, RJ, ZA} {BB, DC, JA, MJ, QA, RA, RJ, ZA} {AC, AD}

The multiset Associative Containers The multiset is the same as the set except that it does not impose the requirement that the items be unique. The insert function always inserts a new item, and duplicate items are retained. However, the erase function removes all occurrences of the specified item because there may be duplicates. The functions lower_bound and upper_bound can be used to select the group of entries that match a desired value. If the item is present, both functions return iterators : lower_bound returns an iterator to the first occurrence of the specified value. upper_bound returns an iterator to the smallest item that is larger than the specified value. The desired entries are between the iterators returned by these two functions. If the item is not present, both upper_bound and lower_bound return an iterator to the smallest element that is larger than the specified entry.

The multiset Associative Containers The following function determines the number of occurrences of the string target in the multiset<string> words_set int count_occurrences(const multiset<string>& words_set, const string& target) { multiset<string>::const_iterator first_itr = words_set.lower_bound(target); multiset<string>::const_iterator last_itr = words_set.upper_bound(target); int count = 0; for (multiset<string>::const_iterator itr = first_itr; itr != last_itr; ++itr) ++count; return count; }

Multisets set1 + set2 is set1 - set2 is set1 * set2 is #include <iostream> #include <string> #include "multiset_functions.h" using namespace std; int main() { multiset<string> set1; multiset<string> set2; multiset<string> set_u; multiset<string> set_d; multiset<string> set_i; string data1[] = { "JA", "BB", "ZA", "QA", "DC", "RJ", "MJ", "AD", "AC", "RA" }; string data2[] = { "GQ", "GQ", "ZA" }; set1.insert(data1, data1 + 10); set2.insert(data2, data2 + 3); set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_u, set_u.begin())); cout << "set1 + set2 is " << set_u << endl; set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_d, set_d.begin())); cout << "set1 - set2 is " << set_d << endl; set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set_i, set_i.begin())); cout << "set1 * set2 is " << set_i << endl; return 0; } Multisets /** Insertion (<<) operator. */ template<typename T> ostream& operator<<(ostream& out, const multiset<T>& a_set) { string prefix = "{"; for (multiset<T>::const_iterator iter = a_set.begin(); iter != a_set.end(); ++iter) out << prefix << *iter; prefix = ", "; } return out << "}"; set1 + set2 is set1 - set2 is set1 * set2 is {AC, AD, BB, DC, GQ, GQ, JA, MJ, QA, RA, RJ, ZA} {AC, AD, BB, DC, JA, MJ, QA, RA, RJ} {ZA}

Comparison of vectors and sets Associative Containers Vectors Sets insert you must specify the location where the item is to be inserted. Position argument is a “hint” to speed up the insertion, but the exact position where the item goes is not under the caller’s control. An iterator that points to the first of the newly inserted element. In addition to the iterator referencing the inserted item, the set’s insert function returns a bool value indicating whether the item was inserted. subscript operator function (operator[]) No subscript operator function (operator[]), therefore, elements cannot be accessed by index. iterators iterate and change through all its elements using an iterator object. Must be type const_iterator - can’t change a set’s contents using an iterator.

Sets and Maps

Associative Containers #include <iostream> #include <string> #include <set> using namespace std; template<typename T> class compare { public: bool operator() (const T& lhs, const T& rhs) { return lhs < rhs; } }; ostream& operator<<(ostream& out, const set<T, compare<T>>& a_set) for (typename set<T>::const_iterator iter = a_set.begin(); iter != a_set.end(); ++iter) out << " " << *iter; } return out; int main() set<string, compare<string>> mySet; string data1[] = { "Apples", "Oranges", "Pineapples", "Peaches", "Apples", "Grapes", "Plums" }; mySet.insert(data1, data1 + data1->size()); cout << "mySet is" << mySet << endl; return 0;

Standard Library Class pair Associative Containers The C++ standard library defines the class pair in the header <utility>. A pair is a simple grouping of two values typically of different types. Since all of its members are public, it is declared as a struct. Pairs are used as the return type from functions that need to return two values, such as the set::insert function, and maps elements. template<typename T1, typename T2> struct pair { T1 first; T2 second; // Construct a default pair. pair() : first(T1()), second(T2()) {} // Construct a default value. pair(const T1& x) : first(x), second(T2()) {} // Construct a pair from two values. pair(const T1& x, const T2& y) : first(x), second(y) {} // Construct an assignable pair template<typename Other_T1, template<typename Other_T2> pair(const pair<Other_T1, Other_T2>& other) : first(other.first), second(other.second) {} }; pair<string,int>(); pair<string,int>("A"); pair<string,int>("A", 65); pair<string,int>(P1);

Associative Containers #include <iostream> #include <set> using namespace std; int main () { set<int> myset; set<int>::iterator it; pair<set<int>::iterator, bool> ret; // set some initial values: for (int i = 1; i <= 5; ++i) myset.insert(i * 10); // set: 10 20 30 40 50 ret = myset.insert(20); // no new element inserted if (ret.second == false) it = ret.first; // "it" now points to element 20 myset.insert (it, 25); // max efficiency inserting myset.insert (it, 24); // max efficiency inserting myset.insert (it, 26); // no max efficiency inserting int myints[]= {5, 10, 15}; // 10 already in set, not inserted myset.insert (myints, myints+3); cout << "myset contains:"; for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << endl; return 0; }