C++ Containers and Iterators

in #cpp3 years ago (edited)

Below is a brief reference to STL containers and iterators. This can be used to get up to speed with containers and iterators in C++.

Containers

A container is an abstract data type that stores a collection of elements. You can think of a container as something that holds and manages the elements you put inside it.

------------------------------------
|             Container            |
------------------------------------
| - element in container -|
| - element in container -|
| - element in container -|
------------------------------------
(the way the elements are stored is based on the type of container)

There are 3 common types of containers; sequence containers, associative containers, unordered associative containers, as well as container adapters.

Sequence Containers

Sequence containers are data structures where elements are accessed sequentially.

Examples:
  • array
  • vector
  • list
  • Associative containers

    Associative containers are sorted data structures where elements can be searched quickly.

    Examples:
  • set
  • multiset
  • map
  • multimap
  • Unordered Associative Containers

    Unordered associative containers are unsorted data structures where elements searched quickly.

    Examples:
  • unordered_set
  • unordered_multiset
  • unordered_map
  • unordered_multimap
  • Container Adaptors

    Container adapters are data structures that gives the programmer a different interface for accesses elements within the adapted container. Thus, you can encapsulate a container with a container adapter and use the adapter to interface with it.

    Examples:
  • stack
  • queue
  • Iterators

    In order to access the elements within a container, you need an iterator. An iterator is a pointer that can point to different elements inside a container.

    Iterators are useful because they can easily be changed for use with different containers.

    Although there are different containers, many of their commonly used member functions have the same name and share similar functionally for brevity.

    One example of this is most containers have the member function .begin() which returns an iterator pointing to the first element and .end() which returns an iterator pointing to the last element.

    Examples in following posts...