You are on page 1of 8

Container Class

A container stores many entities and provide sequential


or direct access to them.
List, vector and strings are such containers in standard
template library.
The string class is a container that holds chars.
All container classes access the contained elements
safely and efficiently by using iterators.

Container class is a class that hold group of same or
mixed objects in memory.

It can be heterogeneous and homogeneous.
Heterogeneous container class can hold mixed
objects in memory whereas when it is holding same
objects, it is called as homogeneous container class.

Example for Container Class

An array
Create a header file
(IntArray.h)
#ifndef INTARRAY_H
#define INTARRAY_H
class IntArray
{
};
#endif

An array container class
http://www.learncpp.com/cpp-tutorial/104-container-classes/
Create constructors for initialization of variables used in the
container.

Use of Assert
Assert is a macro which is useful to check certain conditions
at run time (when the program is under execution) .
To use it the header file assert.h should be included in the
program

Here it is used to check the index to make sure it is valid.
assert(nIndex >= 0 && nIndex < m_nLength);

If this condition is true then the program continues otherwise
program terminates with an error message

An array container class
http://www.programmingsimplified.com/c/source-code/assert
#ifndef INTARRAY_H
#define INTARRAY_H
#include <assert.h>
class IntArray
{
private:
int m_nLength;
int *m_pnData;

public:
//default Constructor
IntArray()
{
m_nLength = 0;
m_pnData = 0;
}
IntArray(int nLength)
{
m_pnData = new int[nLength];
m_nLength = nLength;
}




An array container class
//Parameterized constructor
~IntArray()
{
delete[] m_pnData;
}

void Erase()
{
delete[] m_pnData;
m_pnData = 0;
m_nLength = 0;
}

int& operator[](int nIndex)
{
assert(nIndex >= 0 && nIndex <
m_nLength);
return m_pnData[nIndex];
}

int GetLength() { return m_nLength;
}

};
#endif
#include <iostream>
#include "IntArray.h"

using namespace std;

int main()
{
// Declare an array with 10 elements
IntArray cArray(10);

// Fill the array with numbers 1 through 10
for (int i=0; i<10; i++)
cArray[i] = i+1;

// Resize the array to 8 elements
cArray.Resize(8);

// Insert the number 20 before the 5th
element
cArray.InsertBefore(20, 5);



// Remove the 3rd element
cArray.Remove(3);

// Add 30 and 40 to the end and beginning
cArray.InsertAtEnd(30);
cArray.InsertAtBeginning(40);

// Print out all the numbers
for (int j=0; j<cArray.GetLength(); j++)
cout << cArray[j] << " ";

return 0;
}
Functions to be included in header
files are:
void Reallocate(int nNewLength);
void Resize(int nNewLength);
void InsertBefore(int nValue, int nIndex);
void Remove(int nIndex);
void InsertAtBeginning(int nValue);
void InsertAtEnd(int nValue);
int GetLength();

Refer the program in moodle as a word file named Program for container
class

You might also like