Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 695

19


elements. The standard vector class provides a constructor that accepts the number of
elements as its parameter. So, a vector of 50 students can be defined as follows:


vector MathClass(50);


A compiler allocates enough memory spaces for 50 Students; each element is created
using the default constructor Student::Student().


The number of elements in a vector can be retrieved using a member function size().
For the Studentvector MathClassthat was just defined,Student.size()returns 50.


Another member functioncapacity()tells us exactly how many elements a vector can
accommodate before its size needs to be increased. You will see more on this later.


A vector is said to be empty if no element is in a vector; that is, the vector’s size is zero.
To make it easier to test whether a vector is empty, the vectorclass provides a member
function empty()that evaluates to true if the vector is empty.


To assign a Studentobject Harryto the MathClass, the subscripting operator []is used:


MathClass[5] = Harry;


The subscript starts at 0. As you might have noticed, the overloaded assignment operator
of the Studentclass is used here to assign Harryto the sixth element in MathClass.
Similarly, to find out Harry’s age, access his record using:


MathClass[5].GetAge();


As mentioned earlier, vectors can grow automatically when you add more elements than
they can handle. For instance, suppose one class in your school has become so popular
that the number of students exceeds 50. Well, it might not happen to our math class, but
who knows, strange things do happen. When the fifty-first student,Sally, is added to the
MathClass, the vector can expand to accommodate her.


You can add an element into a vector in several ways; one of them ispush_back():


MathClass.push_back(Sally);


This member function appends the new Studentobject Sallyto the end of the vector
MathClass. Now,MathClasshas 51 elements, and Sallyis placed at MathClass[50].


For this function to work, our Studentclass must define a copy constructor. Otherwise,
this push_back()function will not be able to make a copy of object Sally.


STL does not specify the maximum number of elements in a vector; the compiler ven-
dors are in better positions to make this decision. The vectorclass provides a member
function that tells you what this magic number is in your compiler:max_size().

Free download pdf