Previous Entry Next Entry→

September 12, 2005

Speaking of dynamic arrays, the Standard template library of C++ (STL) provides a vector template class available in C++.  These arrays can be of any of any class and has some useful features.  Include the following the <vector> library to incorporate the vector template.

Here's a little illustration of how it might work with a dynamic array of doubles:

#include <vector> // For the vector<CLASS> class 3
#include <string> // For the string class
#include <iostream>
using namespace std;

int main() {
int j;
// create an array x of doubles with capacity to store 8 numbers.
// All initialized to 0.0.
vector <double> x(8, 0.0);
// assert: x has capacity to store 8 numbers. All are 0.0.
// Assign new values to the first two elements of vector named x
x = 2.6;
x = 5.7;
x = x + x; // Store 8.3
cout << "Enter two numbers: ";
cin >> x >> x;
int n = 5;
// Display the meaningful elements of x--the first n elements
cout << "The first " << n << " elements of x: " << endl;
for(int j = 0; j < n; j++) {
cout << "x[" << j << "]: ";
cout << x[j] << endl;
}
// First set the largest as the first element . . .
double largest = x;
// . . . then compare all other vector elements x through x[n-1]
for(int j = 1; j < n; j++) {
if(x[j] > largest) {
largest = x[j];
}
}
// Display the largest
cout << "The largest element in vector x = " << largest;
char boop;
cin >> boop;
return 0;
}

Which produces this output:

Enter two numbers: 546557 5657657
The first 5 elements of x:
x: 2.6
x: 5.7
x: 8.3
x: 546557
x: 5.65766e+006
The largest element in vector x = 5.65766e+006

============================

Here's another example illustrating the "stack" structure inherent in the vector template.  A class called "node" (which could just as well be a 2D point) is defined and constructors supplied for the crucial purpose of pushing (using member function "push_back()") and popping (with "pop_back()") on/off the stack of vector components.

//File name "node.h":
class node {
public:
double x; // Member of this class, X- Coordinate
double y; // Member of this class Y- Coordinate.
node(); // Default constructor.
//Important Notes:
// 1. We need a constructor if we want to use vector template to this class.
// 2. A header file is meant only for declarations, so u can declare a constructor,
// class functions in a header file. The body of the constructors,
// functions should be in a cpp program file.
};

//File name "node.cpp"
#include "node.h"
node::node(){
x=0.0;   // It takes both x and y.
y=0.0;  // coordinates to be 0.0.
}

// Overloading Constructor 1: In case if we don't specify y coordinate this is used.
node::node(double r){
x=r;   // Assigns r to x.
y=0.0;// Assigns y as 0.0.
}
node::node(double r, double s){
x=r; // Assigns r to x
y=s;// Assigns s to y
}

//File name "mainVector.cpp":
#include <iostream>
#include <vector>
#include "node.h"
using namespace std;
int main() {
// Vector declaration of node. "nodes" is declared to be a vector of type node.

vector<node> nodes;
// Push the x and y coordinates onto the vector of nodes.

nodes.push_back(node());
// Here constructors are used to
// push the values of the members of the class.

nodes.push_back(node(1));
// This is the reason constructors are needed
// to define a vector template to it.

nodes.push_back(node(0,1));
// We have created an array of nodes. The size of array = 4.

nodes.push_back(node(1,1));
for(int i=0;i<4;i++){
cout << "coordinates = (" << nodes[i].x << ", "
<< nodes[i].y << ")\n"; // Print the values of nodes vector.
}
cout << "\n";
nodes.pop_back(); // remove the last element
nodes.push_back(node(1,2)); // Adding this node at the last of the element.
for(int i=0;i<4;i++){
cout << "coordinates = (" << nodes[i].x << ", "
<< nodes[i].y << ")\n"; // Print the values of nodes vector.
}
char a;
cin.get(a);
}

...and here's the output:

coordinates = (0, 0)
coordinates = (1, 0)
coordinates = (0, 1)
coordinates = (1, 1)

coordinates = (0, 0)
coordinates = (1, 0)
coordinates = (0, 1)
coordinates = (1, 2)

#### Member functions

Some commonly used member functions of the vector class are:

 clear size size_type size() const; Returns the number of items (elements) currently stored in the vector. The size_type type is an unsigned integral value. empty bool empty() const; Returns a true value if the number of elements is zero, false otherwise. push_back void push_back(const T& x); Adds the element x at the end of the vector. (T is the data type of the vector's elements.) begin iterator begin(); Returns an iterator (a special kind of object) that references the beginning of the vector. Although the iterator can be used for many things, for now we will just consider its use with erase and sort. end iterator end(); Returns an iterator (a special kind of object) that references a position past the end of the vector. Like begin(), we will just consider its use with erase and sort. erase void erase(iterator first, iterator last); Erase (remove) elements from a vector. For now, we will consider only the case of removing all elements from a vector (see clear() for an alternate way to do the same thing):```vector a; ... a.erase(a.begin(),a.end()); // Remove all elements. ``` void clear (); Erase all elements from a vector. vector a; ... a.clear(); // Remove all elements.

#### Operators

Some of the operators defined for the vector container are:

 = The assignment operator replaces the target vector's contents with that of the source vector:```vector a; vector b; a.push_back(5); a.push_back(10); b.push_back(3); b = a; // The vector b now contains two elements: 5, 10 ``` == Tests whether two vectors have the same content (element-by-element comparison for all elements). [] The subscript operator returns a reference to an element of the vector. A subscript value of zero returns a reference to the first element, and so on. The subscript must be between zero and size()-1. See the example above to see how the subscript operator is used in a loop to access elements of a vector. The subscripted vector may appear on the left or right sides of an assignment (the returned reference is an lvalue):```vector vec; vec.push_back(1.2); vec.push_back(4.5); vec = vec + 5.0; vec = 2.7; // Vector now has two elements: 2.7, 6.2 ```