Check out the new USENIX Web site. next up previous contents
Next: The Coir<Futures> System Up: Generic Programming and the Previous: Functors

Example

STL defines a container template class called vector. It also provides an algorithm called find which takes in three arguments - two input iterators first and last indicating a range, and a value argument val - and returns an iterator pointing to the first position in the range in which the element matches the value val. The following code builds a vector of integer elements, finds the position of the first zero element in the vector, and then the position of the next zero element in the vector.

 ¯

// create a vector with 10 elements

vector<int> v(10);

// add elements to the vector

v.push_back(1);

v.push_back(5);

// point to the first element of the vector

vector::iterator i1 = v.begin();

// the following assertion will be true

assert(*i1 == 1 && *(i1+1) == 5);

// point past the last element of the vector

vector::iterator i2 = v.end();

// find the first zero occurrence

vector::iterator first = find(i1, i2, 0);

if(first == i2)

cout << ``vector has no zeroes'' << endl;

else {

// find the second zero occurrence

vector::iterator second = find(first, i2, 0);

if (second == i2)

cout << ``vector has one zero'' << endl;

else

cout << ``vector has two or more zeroes''

<< endl;

}



Sundaresan Neelakantan
Thu May 15 16:11:49 PDT 1997