gordon college prof. brinton

42
1 Associative Containers Gordon College Prof. Brinton

Upload: sebastian-sykes

Post on 02-Jan-2016

40 views

Category:

Documents


0 download

DESCRIPTION

Associative Containers. Gordon College Prof. Brinton. STL - Assoc. Containers. Set The key is the data set intSet; set keyword; set timeSet; To support the STL container - set; the programmer must overload the == operator and < operator by comparing - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Gordon College Prof. Brinton

1

Associative Containers

Gordon College

Prof. Brinton

Page 2: Gordon College Prof. Brinton

2

STL - Assoc. Containers

• Set– The key is the dataset<int> intSet;set<string> keyword; set<time24> timeSet;

To support the STL container - set; the programmer mustoverload the == operator and < operator by comparingthe key field and giving a Boolean result.

record object

key field other fields

Page 3: Gordon College Prof. Brinton

3

STL - Assoc. Containers

• Map– Stores entries as 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.

map<int, record> studentFile;

studentFile[2343554] = new studentFile;studentFile[2343554].addToBalance(112);

key value

Page 4: Gordon College Prof. Brinton

4

Set and Map

• Both containers do not allow duplicate keys.

• Multiset and multimap (also STL containers) allow duplicate keys)

Page 5: Gordon College Prof. Brinton

5

STL sets and maps

1

2

5

4

3

2

4

53

1

Degenerate search tree red-black tree

Page 6: Gordon College Prof. Brinton

6

STL Set include <set>

• Constructors:set(); default - empty setset(T *first, T *last); use pointers

or iteratorsExamples:

set<int> first; // empty set of intsint myints[]= {10,20,30,40,50};set<int> second (myints,myints+5); // pointersset<int> third (second); // a copy of secondset<int> fourth (second.begin(), second.end()); // iterators into second

Page 7: Gordon College Prof. Brinton

7

STL Set include <set>

• Operations:bool empty() const; void clear(); int size() const;int count(const T& key) const; //return either 1 or

0

iterator find(const T& key);const_iterator find(const T& key) const;// returns either an iterator or end()

NOTE: STL Associative Containers iterators do access the elements in the defined order.

Page 8: Gordon College Prof. Brinton

8

STL Set include <set>

• Operations:pair<iterator, bool> insert(const T& key);// this return a pair object

Example:string t[]={"this","is","a","test"};set<string> s(t,t+4);

pair<set<string>::iterator,bool> result = s.insert("OK");(result.second)?cout << "TRUE":cout << "FALSE";

result = s.insert("OK");(result.second)?cout << "TRUE":cout << "FALSE";

Result:

TRUEFALSE

Page 9: Gordon College Prof. Brinton

9

STL Set include <set>

• Operations:void erase ( iterator position );void erase ( iterator first, iterator last );size_type erase ( const key_type& x ); //returns either 1 or 0

void swap ( set<Key,Compare,Allocator>& st );

• Obtaining the bounds:pair<iterator,iterator> equal_range ( const key_type& x ) const;iterator lower_bound ( const key_type& x ) const; //iterator of first value not < x

iterator upper_bound ( const key_type& x ) const; //iterator of first value > x

Page 10: Gordon College Prof. Brinton

10

STL Set include <set>

• Iterators:

iterator begin(); const_iterator begin(const);

iterator end(); const_iterator end(const);

Page 11: Gordon College Prof. Brinton

11

Set operators

• Union

setC = setA + setB;

setC = 1 2 3 4 5 6 7 8 11 15• Intersection A*B

setC = setA * setB;

setC = 3 5 7 8 11• Difference

setC = setA - setB;

setC = 1 4

1 4

3

57

8 11

3

57

8 1115 2

6

Page 12: Gordon College Prof. Brinton

12

Map include <map>

• Operations are like set’s operations– swap– begin– end– size– empty– operator[] //unlike set– find– erase

See the following examples

Page 13: Gordon College Prof. Brinton

13

#include <string.h>#include <iostream>#include <map>using namespace std;int main(){ map<int, string> Employees; Employees[5234] = "Mike C."; Employees[3374] = "Charlie M."; Employees[1923] = "David D."; Employees[7582] = "John A."; Employees[5328] = "Peter Q.";

cout << "Employees[3374]=" << Employees[3374] << endl << endl; cout << "Map size: " << Employees.size() << endl; for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }}

Page 14: Gordon College Prof. Brinton

14

#include <string.h>#include <iostream>#include <map>

using namespace std;int main(){ map<int, string> Employees; Employees[5234] = "Mike C."; Employees[3374] = "Charlie M."; Employees[1923] = "David D."; Employees[7582] = "John A."; Employees[5328] = "Peter Q.";

cout << "Employees[3374]=" << Employees[3374] << endl << endl; cout << "Map size: " << Employees.size() << endl; for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }}

Employees[3374]=Charlie M.

Map size: 51923: David D.3374: Charlie M.5234: Mike C.5328: Peter Q.7582: John A.

Page 15: Gordon College Prof. Brinton

15

#include <string.h>#include <iostream>#include <map>

using namespace std;

int main(){ map<string, int> Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair<string,int>("David D.",1923)); Employees.insert(map<string,int>::value_type("John A.",7582)); Employees.insert(make_pair("Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl;

for( map<string, int>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }}

Page 16: Gordon College Prof. Brinton

16

#include <string.h>#include <iostream>#include <map>

using namespace std;

int main(){ map<string, int> Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair<string,int>("David D.",1923)); Employees.insert(map<string,int>::value_type("John A.",7582)); Employees.insert(make_pair("Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl;

for( map<string, int>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }}

Map size: 5Charlie M.: 3374David D.: 1923John A.: 7582Mike C.: 5234Peter Q.: 5328

Page 17: Gordon College Prof. Brinton

17

struct cmp_str { bool operator()(char const *a, char const *b) { return strcmp(a, b) < 0; }};

int main(){ map<char *, int, cmp_str> Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair<char *,int>("David D.",1923)); Employees.insert(map<char *,int>::value_type("John A.",7582)); Employees.insert(make_pair((char *)"Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl;

for( map<char *, int, cmp_str>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }}

Page 18: Gordon College Prof. Brinton

18

struct cmp_str { bool operator()(char const *a, char const *b) { return strcmp(a, b) < 0; }};

int main(){ map<char *, int, cmp_str> Employees; Employees["Mike C."] = 5234; Employees["Charlie M."] = 3374; Employees.insert(pair<char *,int>("David D.",1923)); Employees.insert(map<char *,int>::value_type("John A.",7582)); Employees.insert(make_pair((char *)"Peter Q.",5328)); cout << "Map size: " << Employees.size() << endl;

for( map<char *, int, cmp_str>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; }}

Map size: 5Charlie M.: 3374David D.: 1923John A.: 7582Mike C.: 5234Peter Q.: 5328

Could this be ordered differently?

Page 19: Gordon College Prof. Brinton

19

Map details

• Associative ArraysM[“Computer Science”] = 20;

Keys are unique therefore:

M[“Computer Science”] = 26;

replaces the value in the tree for CS.

Page 20: Gordon College Prof. Brinton

20

Map details

• Creating a map:

#include <map>

int main()

{

map<string, double> A;

Page 21: Gordon College Prof. Brinton

21

Map Details• [ ] operator

Steps

1. Search the for map for key

2. If key found, return a reference to the value object associated with key.

3. If key not found, create a new object of type value associated with key, and return a reference to that.

Page 22: Gordon College Prof. Brinton

22

Map Details• [ ] operator

int salary = Employee[“Jack Smith”];

Caution: this will create a new tree entry if it doesn’t exist and assign 0 to variable salary

Page 23: Gordon College Prof. Brinton

23

Map Details• [ ] operator

Better technique:

if (( itr = Employee.find(“Jack Smith”)) == Employee.end()) cout << “ the employee does not exist.” << endl;

Else cout << “Employee Salary: “ << itr->second << endl;

Page 24: Gordon College Prof. Brinton

24

Map Details• Pair Class

1. Contains two public members, first and second

2. Store key/value association

itr->first

itr->second

Page 25: Gordon College Prof. Brinton

25

Map Details• Pair Class

Easiest way to construct pair:

pair<string, int> a;a = make_pair(string(“Jack Smith”), int(100000));

Page 26: Gordon College Prof. Brinton

26

Map Details• Element requirements:

Each key and value must be assignable (an assignment operator which performs a “deep copy”

Deep copytarget of the assignment should be equal but independent of the source

a = b;

the value of a should match b - however if you change a it should not affect b (and vice versa)

Note: if we talking about a linked list then a shallow copy would have two pointers pointing to the same list.

Page 27: Gordon College Prof. Brinton

27

Map Details• Element requirements:

Also each key should adhere to “weak ordering”:

1. A<A is false2. Equality can be determined with (!(A<B) && !(B<A))

Note: only using the less than operator3. If A<B and B<C then A<C must be true

int, char, double, etc. (built-in types) are strict weak ordered

Page 28: Gordon College Prof. Brinton

28

Map Details• Element requirements:

value type used must have a defined default constructor.

map <int, bigNumber>

The built in types have a type of default constructor:

map<int, string>

Page 29: Gordon College Prof. Brinton

29

Map DetailsOperation Description Time

Complexity

swap Swaps elements with another map. This operation is performed in constant time.

Ex: map1.swap(map2);

O(1)

begin Returns an iterator to the first pair in the map.

Ex: itr = map1.begin();

O(1)

end Returns an iterator just beyond the end of the map.

O(1)

Page 30: Gordon College Prof. Brinton

30

Map DetailsOperation Description Time

Complexity

size Returns the number of elements contained by the map. You should use empty() to test whether or not size equals 0, because empty() is faster.

cout << map1.size();

O(n)

empty Returns true if the map contains zero elements.

O(1)

Operator [ ] Accepts a key and returns a reference to the object associated with key. Note that this operator always creates an element associated with key if it does not exist.

O(log n)

Page 31: Gordon College Prof. Brinton

31

Map DetailsOperation Description Time

Complexity

find Accepts a key and returns an iterator to the pair element if found. If the key is not found in the map, this method returns end().

if ( (itr = map1.find("Bob")) == map1.end())

cerr << "Bob was not found in the map." << endl;

else

cout << "Bob was found in the map." << endl;

O(log n)

Page 32: Gordon College Prof. Brinton

32

Map DetailsOperation Description Time

Complexity

erase There are three overloaded forms of this method.

The first accepts a single iterator, and removes the element implied by the iterator from the map. The map should be non-empty. O(1).

map1.erase(map1.begin()); // remove the first element

O(1)

Page 33: Gordon College Prof. Brinton

33

Map DetailsOperation Description Time

Complexity

erase There are three overloaded forms of this method.

The second accepts two iterators, that specify a range of values within the map to be removed. The time complexity is logarithmic plus linear time for the length of the sequence being removed. The two iterators must be valid iterators within the sequence contained by the map. Formally, the range of values [starting, ending) are removed. At worst, this is an O(n) operation.

Ex: map1.erase(map1.begin(), map1.end()); // erase the entire map

O(n)

Page 34: Gordon College Prof. Brinton

34

Map DetailsOperation Description Time

Complexity

erase There are three overloaded forms of this method.

The last accepts an object of the key type, and removes all occurrences of the key from map. Note that since map elements all have unique keys, this will erase at most 1 element. O(log n).

Ex: map1.erase(string("Bob")); // removes all occurrences of "Bob"

O(log n)

Page 35: Gordon College Prof. Brinton

35

Multimap/Multisetbegin endrbegin rendclear emptycountequal_range lower_bound upper_bound insert erasefindmax_sizeoperator=sizeswap

Page 36: Gordon College Prof. Brinton

36

Multimap/Multiset DetailsOperation Description

constructor creates an empty multiset

multiset<int> S

size returns the number of elements

S.size()

insert S.insert( const T& ) : adds an item to the set. If the item is already present, there will be multiple copies in the multiset/multimap

S.insert(6);

Page 37: Gordon College Prof. Brinton

37

Multimap/Multiset DetailsOperation Description

count S.count( const T& t ) : returns the number of times that the item t is found in the set. This will be 0 if the item is not found

erase S.erase( const T& t ) : removes the all items equal to t from the multiset.

erase S.erase( multiset<T>::iterator i ) : removes the item pointed to by i.

S.erase( v ); // ALL: removes all of items == v from the multiset

S.erase( S.find( v ) ); // ONE: removes the first item == v from the multiset

Page 38: Gordon College Prof. Brinton

38

Multimap/Multiset DetailsOperation Description

reverse reverse( iterator begin, iterator end ) : reverses the order of the items:

find S.find( const T& t ) : returns an iterator that points to the first item == t, or S.end() if the item could not be found.

Page 39: Gordon College Prof. Brinton

39

Multimap/Multiset DetailsOperation Description

equal_range S.equal_range(*iter) - returns a pair of iterators such that all occurrences of the item are in the iterator range

pair<multiset <int>::iterator, multiset <int>::iterator > p;

p = S.equal_range(5);

Page 40: Gordon College Prof. Brinton

40

Multimap/Multiset Detailsequal_range

multiset<int>::iterator it; pair<multiset<int>::iterator,multiset<int>::iterator>

ret;

int myints[]= {77,30,16,2,30,30};multiset<int> mymultiset (myints, myints+6); // 2 16 30

30 30 77

ret = mymultiset.equal_range(30); for (it=ret.first; it!=ret.second; ++it) ++(*it); // 2 16 31 31 31 77

Page 41: Gordon College Prof. Brinton

41

Multimap/Multiset Details

• How is multiset implemented?

Multiset:

BST - with integer value representing each occurrence of the element

insert {find - if not present create node else increment count}erase {remove node and report back count}

12

7 20

9 304

(2)

(1)(5)

(2) (3) (1)

HOW WOULD THESE BE HANDLED?clear emptycountfindsize

Page 42: Gordon College Prof. Brinton

42

Multimap/Multiset Details

• How is multimap implemented?

Multimap:

BST - with list or map as the node’s payloadinsert {find - if not present create node else add value to list/set}erase {remove node and report back count}

HOW WOULD THESE BE HANDLED?clear emptycountfindsize

There is not guarantee as to order of duplicates

12

7 20

9 304

(“Tom” -> “Jack” -> “Joe”)

(“Tom”)

(“Jack” -> “Joe”)(“Jack”)

(“Jack” -> “Joe”)

(“Emma”)