Standard Containers

The C++ standard libraries include several very useful standard container classes. Containers are just data structures which hold other things, an they are very useful. The structures are vector, deque (both array-like structures of variable size), list (which is doubly-linked), set, multiset, map and multipmap. The last four allow fast search based on a key, and they are generally implemented using a tree structure.

The 2011 standard added unordered_set, unordered_multiset, unordered_map and unordered_multimap. These are similar in behavior to the existing structures, but based on hashing rather than a tree.

Associated with each container is an appropriate iterator class which allows a program to step through the contents of the container. It is designed to behave much like a pointer, which can be initialized to the first item and incremented in a loop to step through the whole array.

Whatever<cont> col; . . . for(Whatever<cont>::iterator i = col.begin(); i != col.end(); ++i) { // Use *i to access the current item. }

It is also possible to use the list form of the for

Whatever<cont> col; . . . for(cont c: col) { // Use c to access the current item. It is a copy of the // item so changing it won't change the contents of col. }

or

Whatever<cont> col; . . . for(cont & c: col) { // Use c to access the current item. It is a reference to the // item, and assigning it will change the contents of col. }

The way you declare cont is much like the way you declare a function parameter. If you want to change the collection, use a reference. If you don't want to change the collection, but the items are large, declare a const reference.