Lecture Preview: C++ Standard Template Library (STL)

(Suggested book reading: none)

Throughout this course we've used the Stanford libraries, most notably the collection classes. These are not "real" C++ in the sense of being used outside of Stanford. C++ does provide an extensive set of collections and libraries of its own, called the Standard Template Library ("STL"). But we chose not to use them and to use our own collections instead, because they are simpler and friendlier to students than the standard libraries.

Today we'll get a quick introduction to the C++ standard libraries, in case you want to learn more about them on your own. Another great way to learn about these libraries in detail is to take CS 106L, which is a concentrated lab course dedicated to learning proper C++ and its libraries.

A lot of the STL collections are very similar to ours, only with lowercase names and slightly different method names. (See an STL reference for more details.) Here is an example use of the STL vector class:

#include <vector>

// add five integers
vector<int> v;
for (int i = 1; i <= 5; i++) {    // {2, 4, 6, 8, 10}
    v.push_back(i * 2);
}

// insert an element at the start
v.insert(v.begin(), 42);          // {42, 2, 4, 6, 8, 10}

//delete the third element
v.erase(v.begin() + 2);           // {42, 2, 6, 8, 10}

Here is an example use of the STL map class:

#include <map>

// add some key/value pairs
map<string, double> price;
price["snapple"] = 0.75;
price["coke"] = 0.50;

// read from the console and access the map
string item;
double total = 0;
while (cin >> item) {
    total += price[item];
}

// does map contain "coke"?
if (map.find("coke") != map.end()) { ... }
This document and its content are copyright © Marty Stepp, 2018. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the authors' expressed written permission.