You are on page 1of 8

The member functions defined by vector are shown in Table 21-2.

(Again, it is
important not to be put off by the syntax.) Some of the most important member
functions are size( ), begin( ), end( ), push_back( ), insert( ), and erase( ). The
size( ) function returns the current size of the vector. This function is quite useful
because it allows you to determine the size of a vector at run time. Remember, vectors
will increase in size as needed, so the size of a vector must be determined during
execution, not during compilation.

Member Description
template <class InIter> Assigns the vector the sequence defined
void assign(InIter start, InIter end); by start and end.
void assign(size_type num, const T &val); Assigns the vector num elements of
value val.
reference at(size_type i); Returns a reference to an element
const_reference at(size_type i) const; specified by i.
reference back( );
const_reference back( ) const;
Returns a reference to the last element in
the vector.
21
iterator begin( ); Returns an iterator to the first element in
const_iterator begin( ) const; the vector.
size_type capacity( ) const; Returns the current capacity of the
vector. This is the number of elements it
can hold before it will need to allocate
more memory.
void clear( ); Removes all elements from the vector.
bool empty( ) const; Returns true if the invoking vector is
empty and false otherwise.
iterator end( ); Returns an iterator to the end of the vector.
const_iterator end( ) const;
iterator erase(iterator i); Removes the element pointed to by i.
Returns an iterator to the element after
the one removed.
iterator erase(iterator start, iterator end); Removes the elements in the range start
to end. Returns an iterator to the element
after the last element removed.
reference front( ); Returns a reference to the first element in
const_reference front( ) const; the vector.
The Member
Functions allocator_type get_allocator( ) const; Returns vector’s allocator.
Defined by
iterator insert(iterator i, const T &val); Inserts val immediately before the element
vector
specified by i. An iterator to the element is
Table 21-2. returned.
Member Description
void insert(iterator i, size_type num, Inserts num copies of val immediately
const T & val); before the element specified by i.
template <class InIter> Inserts the sequence defined by start and
void insert(iterator i, InIter start, end immediately before the element
InIter end); specified by i.
size_type max_size( ) const; Returns the maximum number of
elements that the vector can hold.
reference operator[ ](size_type i) const; Returns a reference to the element
const_reference operator[ ](size_type i) specified by i.
const;
void pop_back( ); Removes the last element in the vector.
void push_back(const T &val); Adds an element with the value specified
by val to the end of the vector.
reverse_iterator rbegin( ); Returns a reverse iterator to the end of
const_reverse_iterator rbegin( ) const; the vector.
reverse_iterator rend( ); Returns a reverse iterator to the start of
const_reverse_iterator rend( ) const; the vector.
void reserve(size_type num); Sets the capacity of the vector so that it is
equal to at least num.
void resize(size_type num, T val = T ( )); Changes the size of the vector to that
specified by num. If the vector must be
The Member lengthened, then elements with the value
Functions specified by val are added to the end.
Defined size_type size( ) const; Returns the number of elements
by vector currently in the vector.
(continued)
void swap(vector<T, Allocator> &ob); Exchanges the elements stored in the
Table 21-2. invoking vector with those in ob.

The begin( ) function returns an iterator to the start of the vector. The end( )
function returns an iterator to the end of the vector. As explained, iterators are similar
to pointers, and it is through the use of the begin( ) and end( ) functions that you
obtain an iterator to the beginning and end of a vector.
The push_back( ) function puts a value onto the end of the vector. If necessary, the
vector is increased in length to accommodate the new element. You can add elements
to the middle by using insert( ). A vector can also be initialized. In any event, once a
vector contains elements, you can use array subscripting to access or modify those
elements. You can remove elements from a vector by using erase( ).
Here is a short example that illustrates the basic operation of a vector:

// Vector basics.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<int> v; // create zero-length vector
unsigned int i;

// display original size of v


cout << "Size = " << v.size() << endl;

/* put values onto end of vector --


vector will grow as needed */
for(i=0; i<10; i++) v.push_back(i);

// display current size of v


cout << "Current contents:\n";
21
cout << "Size now = " << v.size() << endl;

// display contents of vector


for(i=0; i<v.size(); i++) cout << v[i] << " ";
cout << endl;

/* put more values onto end of vector --


again, vector will grow as needed */
for(i=0; i<10; i++) v.push_back(i+10);

// display current size of v


cout << "Size now = " << v.size() << endl;

// display contents of vector


cout << "Current contents:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
cout << endl;

// change contents of vector


for(i=0; i<v.size(); i++) v[i] = v[i] + v[i];

// display contents of vector


cout << "Contents doubled:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
cout << endl;

return 0;
}
The output of this program is shown here:

Size = 0
Current contents:
Size now = 10
0 1 2 3 4 5 6 7 8 9
Size now = 20
Current contents:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Contents doubled:
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38

Let’s look at this program carefully. In main( ), an integer vector called v is created.
Since no initialization is used, it is an empty vector with an initial capacity of zero.
That is, it is a zero-length vector. This is confirmed by calling the size( ) member
function. Next, 10 elements are added to the end of v by using the member function
push_back( ). This causes v to grow in order to accommodate the new elements. As
the output shows, its size after these additions is 10. Next, the contents of v are displayed.
Notice that the standard array subscripting notation is employed. Next, 10 more
elements are added, and v is automatically increased in size to handle them. Finally,
the values of v’s elements are altered by using standard subscripting notation.
There is one other point of interest in this program: Notice that the loops that display
the contents of v use as their target v.size( ). One of the advantages that vectors have
over arrays is that it is possible to find the current size of a vector. As you can imagine,
this is quite useful in a variety of situations.

Accessing a Vector Through an Iterator


As you know, arrays and pointers are tightly linked in C++. An array can be accessed
through either subscripting or a pointer. The parallel to this in the STL is the link
between vectors and iterators. You can access the members of a vector using either
subscripting or an iterator. The following example shows how:

// Access a vector using an iterator.


#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<char> v; // create zero-length vector
int i;

// put values into a vector


for(i=0; i<10; i++) v.push_back('A' + i);

// can access vector contents using subscripting


for(i=0; i<10; i++) cout << v[i] << " ";
cout << endl;
// access via iterator
vector<char>::iterator p = v.begin();
while(p != v.end()) {
cout << *p << " ";
p++;
}

return 0;
}

The output from this program is

A B C D E F G H I J
A B C D E F G H I J

In this program, the vector is initially created with zero length. The push_back( )
member function puts characters onto the end of the vector, expanding its size as
needed.
Notice how the iterator p is declared. The type iterator is defined by the 21
container classes. Thus, to obtain an iterator for a particular container, you will
use a declaration similar to that shown in the example: Simply qualify iterator
with the name of the container. In the program, p is initialized to point to the
start of the vector by using the begin( ) member function. This function returns
an iterator to the start of the vector. This iterator can then be used to access the
vector an element at a time by incrementing it as needed. This process is directly
parallel to the way a pointer can be used to access the elements of an array. To
determine when the end of the vector has been reached, the end( ) member
function is employed. This function returns an iterator to the location that is one
past the last element in the vector. Thus, when p equals v.end( ), the end of the
vector has been reached.

Inserting and Deleting Elements in a Vector


In addition to putting new values on the end of a vector, you can insert elements into
the middle by using the insert( ) function. You can also remove elements by using
erase( ). The following program demonstrates insert( ) and erase( ):

// Demonstrate insert and erase.


#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<char> v;
unsigned int i;

for(i=0; i<10; i++) v.push_back('A' + i);


// display original contents of vector
cout << "Size = " << v.size() << endl;
cout << "Original contents:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
cout << endl << endl;

vector<char>::iterator p = v.begin();
p += 2; // point to 3rd element

// insert 10 X's into v


v.insert(p, 10, 'X');

// display contents after insertion


cout << "Size after insert = " << v.size() << endl;
cout << "Contents after insert:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
cout << endl << endl;

// remove those elements


p = v.begin();
p += 2; // point to 3rd element
v.erase(p, p+10); // remove next 10 elements

// display contents after deletion


cout << "Size after erase = " << v.size() << endl;
cout << "Contents after erase:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
cout << endl;

return 0;
}

This program produces the following output:

Size = 10
Original contents:
A B C D E F G H I J

Size after insert = 20


Contents after insert:
A B X X X X X X X X X X C D E F G H I J

Size after erase = 10


Contents after erase:
A B C D E F G H I J

Storing Class Objects in a Vector


Although the preceding examples have stored objects of only the built-in types in a
vector, vectors are not limited to this. They can store any type of objects, including those
of classes that you create. Here is an example that uses a vector to store three_d objects.
Introducing the Standard Template Library 511

Notice that the class defines the default constructor, and that overloaded versions of <
and == are provided. Remember, depending upon how your compiler implements the
STL, other comparison operators may need to be defined.

// Store a class object in a vector.


#include <iostream>
#include <vector>
using namespace std;

class three_d {
int x, y, z;
public:
three_d() { x = y = z = 0; }
three_d(int a, int b, int c) { x = a; y = b; z = c; }

three_d &operator+(int a) {
x += a;
y += a;
z += a;

}
return *this; 21
friend ostream &operator<<(ostream &stream, three_d obj);
friend bool operator<(three_d a, three_d b);
friend bool operator==(three_d a, three_d b);
} ;

// Display X, Y, Z coordinates - three_d inserter.


ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << ", ";
stream << obj.y << ", ";
stream << obj.z << "\n";
return stream; // return the stream
}

bool operator<(three_d a, three_d b)


{
return (a.x + a.y + a.z) < (b.x + b.y + b.z);
}

bool operator==(three_d a, three_d b)


{
return (a.x + a.y + a.z) == (b.x + b.y + b.z);
}

int main()
{
vector<three_d> v;
unsigned int i;
Introducing the Standard Template Library 512

// add objects to a vector


for(i=0; i<10; i++)
v.push_back(three_d(i, i+2, i-3));

// display contents of vector


for(i=0; i<v.size(); i++)
cout << v[i];

cout << endl;

// modify objects in a vector


for(i=0; i<v.size(); i++)
v[i] = v[i] + 10;

// display modified vector


for(i=0; i<v.size(); i++)
cout << v[i];

return 0;
}

The output from this program is shown here:

0, 2, -3
1, 3, -2
2, 4, -1
3, 5, 0
4, 6, 1
5, 7, 2
6, 8, 3
7, 9, 4
8, 10, 5
9, 11, 6

10, 12, 7
11, 13, 8
12, 14, 9
13, 15, 10
14, 16, 11
15, 17, 12
16, 18, 13
17, 19, 14
18, 20, 15
19, 21, 16

Vectors offer great power, safety, and flexibility, but they are less efficient than normal
arrays. Thus, for most programming tasks, normal arrays will still be your first choice. But
watch for situations in which the benefits of using vector outweighs the costs.

You might also like