Cours C/C++ container classes

Container Classes

A container class is a data type that is capable of holding a collection of items.
In C++, container classes can be implemented as a class, along with member functions to add, remove, and examine items.
This lecture introduces container classes from Chapter 3. Before this lecture, students should know about these items:
1. How to implement simple classes, such as those in Chapter 2.
2. How to separate the class into a header file and an implementation file.
This lecture presents container classes using an example: the bag class. After this lecture, it would be a good idea to give further coverage of some issues from Section 3.1. In particular, you should cover the use of the typedef in the bag implementation, and the += and + operators, which are not covered in this presentation.

Bags

For the first example, think about a bag.Start by thinking about a bag — a gym bag, a grocery bag, whatever your favorite bag is.
Inside the bag are some numbers.Inside the bag, is a collection of numbers, such as the collection of two fours and an eight shown here.

Initial state of the bag

When you first begin to use a bag, the bag will be empty.
We count on this to be the initial state of any bag that we use.
This bag will be our first example of a container class, which is a class where each object can contain a collection of items (such as numbers). One of the important facets of a container class is that each object begins in a known configuration. In the case of a bag, we will count on each bag being initially empty. This is called the initial state of a bag.

Inserting Numbers into a Bag

Numbers may be inserted into a bag.
We will use a fixed collection of operations to manipulate bags. One of the simplest operations that we permit is the action of inserting a new number into a bag.
In this example, we have inserted the first number — a four — into a bag that was previously empty.
The bag can hold many numbers.We can continue inserting new numbers into the bag.
Now we have a four and an eight in the bag.
We can even insert a second four into the same bag, as shown here.
At this point we have two fours and one eight in the bag of numbers.
I want to make a small point on the side: A bag’s behavior is a bit different than a set of numbers. A set is not allowed to have two copies of the same number. But a bag can have many copies of the same number.

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *