OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
-
date post
21-Dec-2015 -
Category
Documents
-
view
223 -
download
1
Transcript of OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
OOP Etgar 2008 – Recitation 10 3
The STL• The STL is a generic library that provides
efficient data structures and modern algorithms to work with them.
• There are 3 main parts:– Containers manage collections of objects
(list, vector, queue, etc.)– Iterators are objects used to access elements
of containers.– Algorithms are used to process elements of
containers (sort, find, merge, etc.).
OOP Etgar 2008 – Recitation 10 5
Accessing Container Elements
• When we are using containers (data structures), we need a way to access elements within the container.
• With built-in arrays we use index and [] to access any element.
• But when we use generic containers we need a “generic” way to access elements.
OOP Etgar 2008 – Recitation 10 6
Iterators• An iterator is such a generic way – it is an
object that lets us examine elements in a container and navigate from one element to another.– A generalization of index+[] for built-in arrays.
OOP Etgar 2008 – Recitation 10 7
Iterator Types• Each container has its own iterator type.
– There is an iterator type for vectors, another iterator type for lists, and so on.
• The exact type of the iterator for a container is defined as a static member in that container called iterator:
vector<int>::iterator it_vec;
• it_vec above is an object that is used to access elements of a vector<int>.
OOP Etgar 2008 – Recitation 10 8
begin() and end()• To use it_vec to access elements of a
container, we need to “initialize” it with a container.
vector<int> vec;it_vec = vec.begin();
• Containers provide begin() and end() methods, that return iterators to the first and one-past-last elements of the container.
OOP Etgar 2008 – Recitation 10 9
Basic Usage• Iterators are designed to behave just like
pointers – an iterator “points” to an element of the container.– Element access is done using *.– Next element is fetched with ++ (prefer prefix).– Can be compared with ==.
OOP Etgar 2008 – Recitation 10 10
Exampleint main() {
vector<int> v(10); // Vector with 10 elementsvector<int>::iterator iter; // Iterator to vector<int>
// Zero out all v's elementsfor (iter = v.begin(); iter != v.end(); ++iter) {
*iter = 0;}// Sort v's elementssort( v.begin(), v.end() );
return 0;}
OOP Etgar 2008 – Recitation 10 11
Iterator Categories• It’s easy to see there are several categories of
iterators. – vectors can be randomly accessed, so vector iterators
should allow iterator arithmetics.– But this will be too expensive for lists.– Different algorithms require different iterator categories.
• Main iterator categories used in STL are:– Input/Output (Only read/write forward);– Forward (Read and write forward);– Bidirectional (Read and write in both directions);– Random access (Read and write in any place);
OOP Etgar 2008 – Recitation 10 13
Sequence Container vector
• The vector represents a dynamic array:– Random access to elements.– Appending/removing elements at the end is fast.– Inserting/removing in the middle is slow.– Iterator category: Random.
• Main operations:– Random access ([], at()); Stack operations (push_back(),
pop_back()); List operations (insert(pos,elem), erase(pos)); Standard (front(), back(), size(), empty(), swap(), ==).
• Declared in header <vector>.
OOP Etgar 2008 – Recitation 10 14
vector Example#include <iostream>#include <vector>#include <algorithm>using namespace std;
int main() {vector<int> v;
for (int i=1; i<=6; ++i) { v.push_back(i); }
for (vector<int>::size_type i=0; i<v.size(); ++i) {
cout << v[i] << ' ';}
vector<int>::iterator p = find( v.begin(), v.end(), 3 );v.erase(p);
}
OOP Etgar 2008 – Recitation 10 15
Sequence Container list• The list represents a doubly-linked list:
– Insertion/removal at any position is fast.– Random access is not possible.– Iterator category: Bidirectional.
• Main operations:– List operations (insert(pos,elem), erase(pos));
Front operations (push_front(), pop_front()); Stack operations (push_back(), pop_back()); Standard (front(), back(), size(), empty(), swap(), ==).
• Declared in header <list>.
OOP Etgar 2008 – Recitation 10 16
list Example#include <iostream>#include <list>#include <algorithm>using namespace std;
int main() {list<char> l;
for (char c='a'; c<='z'; ++c) { l.push_back(c); }
list<char>::iterator p = max_element( l.begin(), l.end() );cout << "Max element - " << *p << '\n';
while ( ! l.empty() ) {cout <<
l.front() << ' ';l.pop_front();
}}
OOP Etgar 2008 – Recitation 10 17
Associative Container map
• The map contains key/value pairs:– The elements (pairs) are stored sorted (by default,
using operator<())– No front/stack operations, but list operations are fast.– Elements are accessed by the key half of the pair.– The keys must be unique.– Iterator category: Bidirectional.
• Main operations:– Access by key ([]); List operations (insert(elem),
erase(elem)); Standard (size(), empty(), swap(), ==).
• Declared in header <map>.
OOP Etgar 2008 – Recitation 10 18
map Example#include <iostream>#include <map>#include <string>using namespace std;
int main() {map<int, string> m;
m.insert(make_pair(2,"have"));m.insert(make_pair(1,"We"));m.insert(make_pair(4,"map."));m.insert(make_pair(3,"a"));
map<int, string>::iterator p;for (p = m.begin(); p != m.end(); ++p) {
cout << p->second << ' ';}cout << "Yep, a " << m[4]; // Careful - if the key does not exist, it will be created!
}
OOP Etgar 2008 – Recitation 10 20
How They Work• The algorithms are global functions (and not
methods of containers), defined in <algorithm>.• Algorithms operate on ranges of elements:
– E.g. we can sort only half of a container.– A range is specified by an iterator to its first
element, and an iterator to one-past-last element (the range is half-open).
– The caller must ensure that the range is valid.
• Not all containers work with all algorithms.
OOP Etgar 2008 – Recitation 10 21
findInputIteratorfind (InputIterator begin, InputIterator end,
const T& value);
• Finds the first occurrence of the element equal to value in the range, returns iterator to it.
InputIteratorfind_if (InputIterator begin, InputIterator end,
UnaryPredicate op);
• Same as above for element for which the unary predicate op (function or function object with one argument and bool return type) returns true.
• Both return end, if no such element is found.• Complexity: linear.
OOP Etgar 2008 – Recitation 10 22
max_element / min_element
InputIteratormax_element / min_element
(InputIterator begin, InputIterator end);InputIteratormax_element / min_element
(InputIterator begin, InputIterator end,Compare comp);
• Return iterator to max/min element in the range.• First version uses operator<() to compare, second uses
comp().• Complexity: linear.
OOP Etgar 2008 – Recitation 10 23
sort / stable_sortvoidsort / stable_sort (RandomAccessIterator begin,
RandomAccessIterator end);
voidsort / stable_sort (RandomAccessIterator begin,
RandomAccessIterator end,
BinaryPredicate op);
• Sort all elements in the range using operator<() or op().• stable_sort() guarantees the order of equal elements remains
the same.• Cannot be used on lists (no random iterators).• Complexity: n*log(n) on average.
OOP Etgar 2008 – Recitation 10 24
for_eachUnaryOperationfor_each (InputIterator begin,
InputIterator end,
UnaryOperation op);
• Applies the unary function op to each element of the range.
• Returns a copy of op.• Return value of op is ignored.
– If op needs to modify its argument, it must be passed by reference.
• Complexity: linear.
OOP Etgar 2008 – Recitation 10 25
Algorithms Example#include <algorithm>#include <iostream>using namespace std;
void print(int i) { cout << i << ' '; }
struct MoreThan1 { bool operator()(int i) { return i > 1; } };
int main() { int a[5] = {5, 4, 1, 3, 2};
sort(&a[0], &a[5]); // Note a[5] - one-past-last element
for_each(&a[0], &a[5], print);
cout << '\n' << *( find_if(&a[2], &a[5], MoreThan1() ) );
return 0;}