FAQ 2.15 What are the basics of using container classes?

graphics/new_icon.gif

Templates are one of the most powerful code reuse mechanisms in C++. The most common use for templates is for containers. Container classes are used to create objects that hold other objects. There are many different container templates, including linked lists, vectors (arrays), sets, and maps. Container templates allow programmers to get the benefits of sophisticated data structures, such as binary trees that always stay balanced, hash tables, skip lists, and splay trees, without having to know anything at all about the details of those data structures.

Templates look a little funny at first, but they're not that much different from normal classes once you get used to them. The only strange part is the angle brackets: a vector of Car is declared using the syntax vector<Car>. The typedef syntax is used for convenience: it creates easy-to-read synonyms such as CarList.

 #include <vector>                                    <-- 1 #include <string>                                    <-- 2 #include <algorithm> using namespace std; #include "Car.hpp"                                   <-- 3 typedef vector<Car>    CarList;                      <-- 4 typedef vector<string> StringList;                   <-- 5 int main() {   CarList x;                                         <-- 6   Car a, b, c;   x.push_back(a);                                    <-- 7   x.push_back(b);   x.push_back(c);   // ...   StringList y;                                      <-- 8   y.push_back("Foo");                                <-- 9   y.push_back("Bar");   y.push_back("Baz");   sort(y.begin(), y.end());                          <-- 10   // ... } 

(1) Get the standard vector template

(2) Get the standard string class

(3) Get the user-defined Car class

(4) Synonym for convenience

(5) Synonym for convenience

(6) Create a vector of Car objects

(7) Append object a to the CarList x

(8) Create a vector of string objects

(9) Append string "Foo" to the StringList y

(10) Sort the StringList y

This sample code creates two vector objects: x is a vector of Car objects and y is a vector of string objects. This is analogous to creating two C-like arrays (Car x[3]; and string y[3];), but vector objects are more flexible, they can grow to an arbitrary size, they are safer, and they have a lot more services associated with them. See FAQ 28.13.

UML uses the following notation to show a template vector along with instantiations of that template vector<Car> and vector<string>.

graphics/02fig02.gif



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net