CSE 40872 Lecture 004

Topic:Data Structures (STL, Vectors, Deques)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 02, 2009

Standard Template Library (STL)

C++ library of commonly used data structures and algorithms.

STL Containers

Collection of elements of a particular type.

vector<int>         mVector;
map<string, int>    mMap;
list< set<double> > mListOfSets;

Templates (i.e ``<Type>``) allow customization and optimization of data structures.

Common Methods

mVector.push_back(12345);
mVector.clear();
mVector.size();

Iterators

Used throughout STL, so get used to them.

Example

Print items in a vector:

for (int i = 0; i < mVector.size(); i++)
    cout << mVector[i];

vector<int>::iterator it;
for (it = mVector.begin(); it != mVector.end(); it++)
    cout << *it;

copy(mVector.begin(), mVector.end(), ostream_iterator<int>(cout, " "));

Another Example

Reverse a vector

reverse(mVector.begin(), mVector.end());

Reverse a string

reverse(mString.begin(), mVector.end());

STL Vector

Provides array-like container:
  • Contiguous block of memory.
  • Random access is O(1).
  • Insertion O(1) at the end but O(n) elsewhere.
  • Automatic and dynamic memory management.
  • Modifying container will invalidate iterators.

STL Deque

Like vector but supports O(1) insertion and deletion at the beginning of container:

mDeque.push_back(1);
mDeque.push_front(2);   // Not supported by vector
mDeque.pop_front();     // Not supported by vector
mDeque.pop_back();

Complete deque example.

Summary