C++ Standard Template Library

The Standard Template Library (STL)

Sequence container common operations

Requirements of base data type: copy constructor, = , == , <, default constructor for initialization

Basic template concepts

Vector Type

Advantages of using vector</code:

Disadvantage: lacks fast insert/delete from middle.

Examples of declaring and using vectors:

vector<int> v;        // v is an empty vector of ints
vector<int>::size_type vsize;

const int SIZE=5;
int a[SIZE] = {2, 3, 4, 5, 6};
vector<int> v(a, a+SIZE);// initializes v to the contents of array a

vector<int> v(10);       // vector size 10, elements initialized to 0 default
vector<int> v2(10, 5);   // vector size 10, init to 5

if (v.empty())
        v.assign(10, 2);    // size 10, init to 2
v.assign(a, &a[SIZE]);
v.assign(v2.begin(), v2.end());

v.resize(25, 2);         // add elements init to 2, size 25
v.reserve(25);           // capacity 25, no init

Iterators

Example:

#include <vector> 
#include <iostream> 
using namespace std;

int main(void) {
    vector<double>; dv = {1.1,2.2,3.3,4.4,5.5};
    vector<double>::iterator di = dv.begin();
    di++;                  // di now points to 2.2
    di = di + 3;           // similar to pointer arithmetic on arrays; di now at the 5.5
    di = dv.erase(di);     // delete the item pointed to by di, make di point to next element in dv
    // dv now { 1.1 2.2 3.3 4.4 }
    dv.insert(di,3.3);     // insert before di; means at end since di at end now
    // dv now { 1.1 2.2 3.3 4.4 3.3 }

    di = dv.begin();
    while (di != dv.end()) { cout << *di << " "; di++; }
    cout << endl;
}

Lists

A few more STL details

Algorithms in STL

Searching/sorting algorithms

void sort(is, ie)
void sort(is, ie, bool func(valtype, valtype))
iter find(is, ie, val)    // returns iter to 1st occurrence of val in range
iter find_if(is, ie, bool func(valtype))
bool binary_search(is, ie, val) // container must be sorted first
bool binary_search(is, ie, val, bool func(valtype, valtype))

Sorting Lists

Example:
bool compare(const Card & x, const Card & y) { 
  return x.face  <  y.face;
}

sort(hand.begin(), hand.end(), compare);

Associative Containers, briefly