Title: Sets
1Sets MapsAssociative Containers
- Briana B. Morrison
- Adapted from Alan Eugenio
2(No Transcript)
3(No Transcript)
4Sets
5Sets defined by a key along with other data
6(No Transcript)
7(No Transcript)
8CLASS set
ltsetgt
Operations
bool empty() const Is the set empty?
int size() const Return the number of elements
in the set.
9Set Example
- int arr 4, 8, 9, 2
- int arrSize sizeof(arr)/sizeof(int)
- setltintgt setA, setB(arr, arrarrSize)
- cout ltlt setB.size()
- if (setA.empty())
- coutltlt A is empty ltlt endl
10(No Transcript)
11Set Example
- int arr 4, 8, 9, 2
- int arrSize sizeof(arr)/sizeof(int)
- setltintgt setA, setB(arr, arrarrSize)
- setltintgtiterator iter // set iterator
- cout ltlt setB.count(8)
- cout ltlt setA.count(0)
- iter setB.find(2)
- cout ltlt iter ltlt endl
- iter setB.find(12)
- cout ltlt iter ltlt endl
// output 1 (or true)
// output 0 (or false)
// what does iter point to?
12pairltiterator, boolgt insert(const T key) If
key is not in the set, insert it and then 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 set.
int erase(const T key) If key is in the set,
erase it and return 1 otherwise, return
0. Postcondition The set size decreases by 1
if key is in the set.
13(No Transcript)
14Set Example
- int arr 4, 8, 9, 2
- int arrSize sizeof(arr)/sizeof(int)
- setltintgt setA, setB(arr, arrarrSize)
- setltintgtiterator iter // set iterator
- setA.insert(12)
- setA.insert(12) // what happens?
- setA.insert(13)
- cout ltlt setA.size()
- setB.erase(9)
- iter setB.begin()
- setB.erase(iter)
- setB.erase(setB.begin(), setB.end())
- setB.erase(iter)
15(No Transcript)
16Set Example
- int arr 4, 8, 9, 2
- int arrSize sizeof(arr)/sizeof(int)
- setltintgt setA, setB(arr, arrarrSize)
- setltintgtiterator iter // set iterator
- // iterator points at smallest element with value
2 - iter setB.begin()
- iter // position iter at next element
- cout ltlt iter
- iter setB.end()
- iter--
- cout ltlt iter
- setA setB // use assignment operator
// output 4
// set iter at end of list
// output 9 (largest element)
17Performance
- For find, insert, and erase, worstTime(n) is
logarithmic in n.
18Another Set Example
- string str associative
- setltchargt charSet
- setltchargtiterator iter
- for (int i 0 i lt str.length() i)
- charSet.insert(stri)
- // length of string is ? size of set is ?
- cout ltlt str.length() ltlt ltlt charSet.size()
- if (charSet.count(t) 1)
-
- cout ltlt Erase t from the set ltlt endl
- charSet.erase(t) // remove t from set
-
- iter charSet.find(s) // locate s in the
set - charSet.erase(iter) // remove s from set
- iter charSet.find(x)
- charSet.erase(iter) // what happens?
19Sieve of Eratosthenes
- Application using sets
- Method using sets to find all prime numbers lt n.
- Initialize a set to contain all of the integers
in the range 2 to n. - Make multiple passes over the elements in the
set, using successive integer key values 2, 3, 4,
- Each pass shakes free nonprime numbers and let
them filter through the sieve. At the end,
only the prime numbers remain.
20Sieve of Eratosthenes
21Set Functions
- The following set functions are NOT implemented
in the STL class, but can be implemented using
fairly simply using logic. In fact, your text
has already implemented them in their library
d_setops.h
22Set-Union Operator (A B) The set of all
elements x such that x is an element in set A OR
x is an element in set B. Example A B 1,
2, 3, 6, 8, 9, 10
Set-Intersection Operator (A B) The set of
all elements x such that x is an element in set A
and x is an element in set B. Example A B
3, 9
Set-Difference Operator - (A - B) The set of
all elements x such that x is an element in set A
but x is not an element in set B. Example A - B
1, 8, 10
23Union Implementation (Easy)
- template lttypename Tgt
- setltTgt operator (const setltTgt lhs, const
setltTgt rhs) -
- setltTgt setUnion // construct union
- // iterators that traverse the sets
- setltTgtconst_iterator rhsIter
rhs.begin() -
- setUnion lhs // insert everything from lhs
- while (rhsIter ! rhs.end())
- setUnion.insert(rhsIter)
- return setUnion
-
24Union Implementation (MergeSort)
- template lttypename Tgt
- setltTgt operator (const setltTgt lhs, const
setltTgt rhs) -
- setltTgt setUnion // constuct union
- // iterators that traverse the sets
- setltTgtconst_iterator lhsIter
lhs.begin(), - rhsIter rhs.begin()
25- // move forward until you reach end of either set
- while (lhsIter ! lhs.end() rhsIter !
rhs.end()) - if (lhsIter lt rhsIter)
- // lhsIter belongs to the union. insert
and move - // iterator forward
- setUnion.insert(lhsIter)
- else if (rhsIter lt lhsIter)
- // rhsIter belongs to the union. insert
and move - // iterator forward
- setUnion.insert(rhsIter)
- else
- // the two values are equal.
insert just one and move - // both itertors forward
- setUnion.insert(lhsIter)
- rhsIter
-
26- // flush any remaining items
- if (lhsIter ! lhs.end())
- while (lhsIter ! lhs.end())
- setUnion.insert(lhsIter)
- else if (rhsIter ! rhs.end())
- while (rhsIter ! rhs.end())
- setUnion.insert(rhsIter)
- return setUnion
-
27Set Functions in ltalgorithmgt
28Set Example
- int main()
-
- setltstringgt set1
- setltstringgt set2
- setltstringgt set_u
- setltstringgt set_d
- setltstringgt set_i
- string data1 "Apples", "Oranges",
"Pineapples" - string data2 "Peaches", "Apples",
"Grapes" - set1.insert(data1, data13)
- set2.insert(data2, data23)
- cout ltlt "set1 is " ltlt set1 ltlt endl
- cout ltlt "set2 is " ltlt set2 ltlt endl
- set_union(set1.begin(), set1.end(),
- set2.begin(), set2.end(),
- inserter(set_u, set_u.begin()))
29Set Example (2)
- set_difference(set1.begin(), set1.end(),
- set2.begin(), set2.end(),
- inserter(set_d, set_d.
begin())) - cout ltlt "set1 - set2 is " ltlt set_d ltlt endl
-
- set_intersection(set1.begin(), set1.end(),
- set2.begin(), set2.end(),
- inserter(set_i, set_i.
begin())) - cout ltlt "set1 set2 is " ltlt set_i ltlt endl
-
- bool is_member (set1.find(string("Apples"))
! set1.end()) - cout ltlt "\"Apples\" is an element of set1 is "
- ltlt boolalpha ltlt is_member ltlt endl
- return 0
-
30vector vs. set
- Sets allow no duplicates
- Sets do not have positions, so no operator
- Set iterator can produces elements in sorted order
31(No Transcript)
32(No Transcript)
33The stdpair
- The stdpair is defined in ltutilitygt
- It is a struct (data members are public) that
contains two data items first and second. - There is a template function make_pair that can
be used to construct pair objects.
34(No Transcript)
35(No Transcript)
36(No Transcript)
37(No Transcript)
38(No Transcript)
39(No Transcript)
40(No Transcript)
41(No Transcript)
42(No Transcript)
43(No Transcript)
44(No Transcript)
45(No Transcript)
46(No Transcript)
47(No Transcript)
48(No Transcript)
49(No Transcript)
50Exercises
- Suppose there is a Coin class and we want a set
that is ordered in reverse size (dime, then
penny, then nickel, then quarter). How could we
implement this? - setltCoin, ???gt coinSet
- We need a function class that will do the
comparison.
51Exercises
- Assume that aList is a list of type T. Implement
the function removeDuplicates() by declaring a
set of type T and copying the elements from aList
into the set. Copy the elements from the set
back to the list so that the nonduplicate
elements appear in descending order.
52- Assume that setA and setB are setltchargt objects
consisting of the distinct letters found in
strings strA and strB, respectively. This
exercise uses expressions that combine set
operations. For instance, the expression - setC setA setA setB
- Assigns to setC all of the letters that are in
strA, but not in strB. - Assign to setC all of the characters in the two
strings that are not found in both strings. - Declare a set called setVowels that contains the
letters a, e, i, o, and u. Assign to setD all
vowels that are not found in strA. - Assign to setE all vowels that are in either strA
or strB. - Assign to setF the consonants that are in the
strings.
53Maps
54Key-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.
55Key-Value Example
56Maps
57Map Picture
58(No Transcript)
59Map APIs
- Following are the APIs for the map class.
- You will notice they are almost identical to the
interface for the set class.
60The map functions
- Template parameters
- Key_Type The type of the keys
- Value_Type The type of the values
- Compare The function class that compares the
keys. - All functions defined for the set are defined for
the map, taking a pairltKey_Type, Value_Typegt. - The index operator (operator) is also defined
for the map.
61CLASS map
ltmapgt
Operations
bool empty() const Is the map empty?
int size() const Return the number of elements
in the map.
62(No Transcript)
63pairltiterator, boolgt insert(const pairltkey,Tgt
key) If key is not in the map, insert it and
then 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 map size increases
by 1 if key is not in the map.
int erase(const key_type key) If key is in the
map, erase it and return 1 otherwise, return
0. Postcondition The map size decreases by 1
if key is in the map.
64(No Transcript)
65(No Transcript)
66(No Transcript)
67(No Transcript)
68(No Transcript)
69(No Transcript)
70(No Transcript)
71(No Transcript)
72T operator (const value_type x) Access the
item with key x in this map. Postcondition If
there is a pair with key x in this
map, a reference to the second
component in that pair has been
returned. Otherwise, the pair ltx,
T()? Has been inserted in this map and
a reference to the second
component in that pair has been
returned. The worstTime(n) is O(log
n).
73(No Transcript)
74The map operator
- The map can be used like an array, except that
the Key_Type is the index. - Example
- mapltstring, stringgt a_map
- a_map"J" "Jane"
- a_map"B" "Bill"
- a_map"S" "Sam"
- a_map"B1" "Bob"
- a_map"B2" "Bill"
- Note
- If a mapping exists, assignment will replace it.
- If a mapping does not exist, a reference will
create one with a default value.
75Map code example
- map ltstring, stringgt phoneBook
- mapltstring, stringgtconst_iterator it1
- string name1 Smith, John
- string name2 Thompson, Julia
- string phone1 212-555-4444
- string phone2 806-555-6565
- phoneBookname1 phone1
- phoneBookname2 phone2
76- for (it1 phoneBook.begin() it1 !
phoneBook.end() it1) -
- cout ltlt it1-gtfirst ltlt \t ltlt it1-gtsecond ltlt
endl -
- it1 phoneBook.find(string(name2))
- if (it1 ! phoneBook.end())
- cout ltlt Search for ltlt it1-gt first ltlt
- phone number ltlt endl
- ltlt it1-gt second ltlt endl
77Exercises
- Use the array strList of strings along with a
mapltstring,intgt object mLength to write code
segments that perform designated tasks - string strList store, map, array,
set, multimap, string - int strListSize sizeof(strList) /
sizeof(string) - mapltstring, intgt mLength
- int i
- Write a loop that enters each string from the
array into the map as the key-value pair (string,
string length). - Declare an iterator that locates elements in the
map mLength. Use the iterator to output all
strings that have a length of 5.
78- Multi-sets and multi-maps
- A multi-set is similar to a set, but allows
duplicates. - A multi-map is similar to a map, but allows
duplicates. - (Only differences to APIs are shown, all other
functions are available.)
79(No Transcript)
80(No Transcript)
81(No Transcript)
82(No Transcript)
83(No Transcript)
84(No Transcript)
85(No Transcript)
86Example of a multiset
- int count_occurences(const multisetltstringgt
words_set, - const string target)
-
- multisetltstringgtconst_iterator first_itr
- words_set.lower_bound(target)
- cout ltlt "first_itr " ltlt
- (first_itr ! words_set.end() ?
first_itr - "end()") ltlt endl
- multisetltstringgtconst_iterator last_itr
- words_set.upper_bound(target)
- cout ltlt "last_itr " ltlt
- (last_itr ! words_set.end() ? last_itr
- "end()") ltlt endl
- int count 0
- for (multisetltstringgtconst_iterator itr
first_itr - itr ! last_itr itr)
- count
- return count
-
87(No Transcript)
88(No Transcript)
89(No Transcript)
90(No Transcript)
91(No Transcript)
92(No Transcript)
93Exercises
- a) Let ms be a multiset of type T. Write a code
segment that outputs the distinct elements of ms
along with their count in the form - element1(ltcount1gt) element2(ltcount2gt)
element3(ltcount3gt) - For example if ms contains the elements from
the array arr 2, 1, 3, 3, 1, 3, 5, 2, 3, 6 ,
the output is - 1(2) 2(2) 3(4) 5(1) 6(1)
- Modify the output from part a) so that the
distinct elements are output one per line, with
duplicates repeated on the line. Using array arr
as the example - 1 1
- 2 2
- 3 3 3 3
- 5
- 6
94- Describe the action of function f().
- template lttypename Tgt
- T f(const multisetltTgt ms, const T item)
-
- multisetltTgtconst_iterator iter
- pair ltmultisetltTgtconst_iterator,
multisetltTgtconst_iteratorgt p - T total T()
- p ms.equal_range(item)
- for (iter p.first iter ! p.second iter)
- total iter
- return total
95Summary Slide 1
- Set and map associative containers - Both
store and retrieve data by value rather by
position. - A set is a collection of keys,
where each key is unique. - A map is a
collection of key-value pairs that
associate a key with a value. - In a
map, there is only one value associated with a
key.
95
96Summary Slide 2
- Set and map implementation - Binary search
tree ideal, since it is an associative
container and its iterators traverse its value
in order.
96
97Summary Slide 3
- Map - Often called an associative array
because applying the index operator with
the key as its argument accesses the
associated value.
97
98Summary Slide 4
- Multiset - Like a set, except a key can
occur more than once. - The member
function count() and equal_range() deal with
duplicate values.
98
99Summary Slide 4
- Multimap - Like a map, except a key can
occur more than once. - No overloaded
operators
99