Chapter 23 - The Standard Template Library - Containers


Chapter Goals



23.1 The Standard Template Library (STL)


23.1.1 STL Container Categories

3 categories of containers:

  1. Fundamental (or sequential)
    • vector, list, deque (pronounced "deck")
  2. Adapters
    • Layered on top of the fundamental containers
    • stack, queue, priority queue
  3. Associative
    • set, map

23.2 The Fundamental Containers


23.2 The Fundamental Containers (cont.)

Operation Vector List Queue
container() O(1) O(1) O(1)
container(size) O(1) O(n) O(1)
container(size, value) O(n) O(n) O(n)
at(int) O(1)   O(1)
back() O(1) O(1) O(1)
begin() O(1) O(1) O(1)
capacity() O(1)    
clear() O(1) O(1) O(1)
empty() O(1) O(1) O(1)

23.2 The Fundamental Containers (cont.)

Operation Vector List Queue
end() O(1) O(1) O(1)
erase(iterator) O(n) O(1) O(n)
erase(iterator, iterator) O(n) O(1) O(n)
front() O(1) O(1) O(1)
insert( iterator, value) O(n) O(1) O(n)
pop_back() O(1) O(1) O(1)
pop_front()   O(1) O(1)
push_back(value) O(1)+ O(1) O(1)+
push_front(value)   O(1) O(1)+

23.2 The Fundamental Containers (cont.)

Operation Vector List Queue
rbegin() O(1) O(1) O(1)
rend() O(1) O(1) O(1)
resize() O(n)   O(n)
size() O(1) O(1) O(1)
operator[]() O(1)   O(1)
operator=(container) O(n) O(n) O(n)

O(1)+ - means amortized constant time


23.2 The Fundamental Containers (cont.)

C'tors
Default creates an empty container
Integer arg. creates container with size elements, initialized to default value
  • 2nd form allows explicit initialization. Same for all elements
Can be initialized with another collection
at
checks for index validity, unlike operator[]
front, back
return the first and last elements
empty
returns true if container has no elements

23.2 The Fundamental Containers (cont.)

erase
removes specified element(s), returns iterator to next element
insert
inserts element prior to the iterator
push_front, push_back
insert values at the front and back
pop_front, pop_back
remove them
rbegin, rend
return reverse_iterators

23.2 The Fundamental Containers (cont.)


23.2.1 Vectors


23.2.1 Vectors - Sieve of Eratosthenes


Advanced Topic 23.1


Implementation of Vector


23.2.2 Lists


23.2.2 Lists (cont.)

Operations unique to list:

Operation Description
merge(list) Merge the current (sorted) list with the (sorted) argument list
remove(value) Remove all instances of the given value
remove(pred) Remove values for which pred returns true
reverse() Reverse order of elements
sort() Place the values into sorted order
sort(comp) Place values in order using comp
splice(iter, list) Splices argument list into the list at given location
unique() Remove duplicate copies of values from sorted list
unique(pred) Remove duplicate values from list sorted w/pred

23.2.2 Lists - Example

Simple inventory mgt. system; products have unique IDs. Tasks:
- Process an order for a product #
- Process the shipment of a given product.


23.2.2 Lists - Example


23.2.3 Deque


23.2.3 Deque - Example

Example: time-driven simulation of the line in front of a tellers' counter at a bank.


23.2.3 Deque - Example


Advanced Topic 23.3


Implementation of Deque


23.3 The Stack and Queue Adapters


23.3 (cont.) - stack implementation

template <class T, class C = deque<T> >
class stack
{
public:
   int size() const;
   void push(const T& x);
   T& top();
   void pop();
protected:
   C values;
};

23.3 (cont.) - stack implementation

template <typename T, typename C>
int stack<T, C>::size() const
{
   return values.size();
}

template <typename T, typename C>
void stack<T, C>::push(const T& x)
{
   values.push_back(x);
}

23.3 stack implementation (cont.)

template <typename T, typename C>
T& stack<T, C>::top()
{
   return values.back();
}

template <typename T, typename C>
void stack<T, C>::pop()
{
   values.pop_back();
}

23.3 stack implementation (cont.)


23.3 (cont.) - stack Example

Reverse Polish Notation (RPN, or postfix) calculator


23.3 (cont.) - stack Example


23.4 Sets


23.4 Set Operations

Operation Description
set() Construct an empty set
set(iterator, iterator) Construct a set from the given range of values
begin() Return iterator for set
count(value) Return number of instances of value
empty() Return true if set is empty
end() Return ending iterator for set
erase(iterator) Erase position from set

23.4 Set Operations (cont.)

Operation Description
erase(value) Erase value from set
find() Return iterator for value
insert(value) Insert value into set
rbegin() Return iterator for values in reverse order
rend() Return ending iterator for values in reverse order
size() Return number of elements in set

23.4 Sets (cont.)


23.4 Sets (cont.)

2 ways to form sets of a new object type. Using the Employee class for our example.

  1. Override operator<, allowing the normal declaration:
    bool operator< (const Employee& a, const Employee& b)
    {
       return a.salary() < b.salary();
    }
    
    set<Employee> workers; // Will be sorted by salary

23.4 Sets (cont.)

  1. Provide an explicit function object; name it as the second template argument
    class SortByName
    {
    public:
       bool operator() (const Employee& a, const Employee& b) const;
    };
    
    bool SortByName::operator(const Employee& a, const Employee& b)
    {
       return a.get_name() < b.get_name();
    }
    
    set<Employee, SortByName> workers; // Now sorted by name

23.4 Sets - Dictionary Example

Program to check for misspelled words. A dictionary is read into a set, then checks input words against the set.

void spellCheck(istream& dictionary, istream& text)
{
   set<string> words;
   string word;

   // First put all words from dictionary into set.
   while (dictionary >> word)
      words.insert(word);

   // Then read words from text
   while (text >> word)
      if (words.count(word) == 0)
         cout << "Misspelled word " << word << "\n";
}

23.5 Maps


23.5 Maps (cont.)


23.5 Maps (cont.)


23.5 Maps - Operations

Operation Description
map() Construct an empty map
map(iter, iter) Initialize a new map from the given range of values
begin() Return iterator
count(key) Return number of entries with key (0 or 1)
empty() Return true if collection is empty
end() Return ending iterator
erase(iter) Erase value at indicated location
erase(iter, iter) Erase range of values

23.5 Maps - Operations (cont.)

Operation Description
find(key) Return iterator to value with key
insert(elem) Insert elem, which must be a key/value pair
lower_bound(key) Return iterator for first entry with key (multimap only)
rbegin() Return iterator in reverse order
rend() Return ending iterator in reverse order
size() Number of elements in container
upper_bound(key) Return iterator for past-the-end entry with key (multimap only)
operator[key] Return value associated with key

23.5 Maps - Example

Consider a directory listing of telephone numbers.


23.5 Maps - Example (cont.)


23.5.1 Priority Queue


23.5.1 Priority Queue (cont.)


23.5.1 Priority Queue - Example


23.5.1 Priority Queue (event.h)


23.5.1 Priority Queue - Example


23.5.1 Priority Queue (event.cpp)


23.5.1 Priority Queue - Example


23.5.1 Priority Queue (hotdog.cpp)


23.6 Case Study: Dijkstra's Shortest Path Algorithm


23.6 Case Study: Graph Representation


23.6 Case Study: Graph Representation

class DistanceToCity
{
public:
   DistanceToCity(string n, int d);
   string name;
   int distance;
   bool operator<(const DistanceToCity& right) const;
};

23.6 Case Study: Graph Representation (cont.)

DistanceToCity::DistanceToCity(string n, int d)
{
   name = n;
   distance = d;
}

bool DistanceToCity::operator<(const DistanceToCity& right) const
{
   return right.distance < distance;
}

23.6 Case Study: Graph Representation (cont.)


23.6 Case Study: Dijkstra's Algorithm


23.6 Case Study: Dijkstra's Shortest Path Algorithm (dijkstra.cpp)


Chapter Summary


  1. STL - a library of classes that represent containers that occur frequently in computer programs in all application areas.
  2. Each class in the STL supports a relatively small set of operations. Basic functionality is extended through the use of generic algorithms.
  3. The 3 fundamental data structures are the vector, list, and deque.
  4. Vector and deque are indexed data structures; they support efficient access to each element based on an integer key.
  5. A list supports efficient insertion into or removal from the middle of a collection. Lists can also be merged with other lists.

Chapter Summary (cont.)


  1. Stacks, queue, and priority queues are adapters built on top of the fundamental collections. A stack enforces the LIFO protocol, while the queue uses FIFO.
  2. A set maintains elements in order. Permits very efficient insertion, removal, and testing of elements.
  3. A map is a keyed container. Entries in a map are accessed through a key, which can be any ordered data type. Associated with each key is a value. A multimap allows more than one value to be associated with a key.
  4. A priority queue is a collection organised so as to permit fast access to and removal of the largest element.