Exploding Rats and the C++ Standard Vector

Rats are small, cheap, easy to maintain and transport.

Mine-sniffing ratsAs many are aware, land mines present a significant danger in many war-ravaged countries around the world. Numerous innovative techniques have been developed to clear mine fields, rendering the land once again usable and preventing tragic injuries and deaths. A Belgian non-profit organization, APOPO, began a unique program to develop a new method — using Giant Pouched Rats (Nesomyidae Cricetomyinae) to detect mines — dubbed HeroRATS in 2004, and has now deployed the intrepid rodents in Mozambique.

The rats are too light to set off mines, so disappointingly they are not destroyed in the process (sorry, I lied). Instead, the rats are attached to guide lines and trained to scratch at the ground when they sniff out explosives. The mine is then flagged for removal using more appropriate tools.

A zebra is a horse designed by a committee.

I’ll be the first to admit that I am not an expert with the C++ language. In fact, I can use all the practice I can get. I’ve been using the Standard Template Library on and off for almost 3 years now, but know embarrassingly little about it’s full capabilities. In that vein, I will (hopefully) be posting a series of snippets and short programs about the STL. I plan to start simple, and work my way up. Without further ado, the very basics of the STL vector and it’s iterator.

#include 
#include 
#include 
 
int main()
{
   // Define a vector, which is an array-like container of items.
   // Unlike std::set, vectors can contain the same element any
   // number of times.
   std::vector<std::string> strings;
 
   // Add some strings to the vector.
   strings.push_back("foo");
   strings.push_back("bar");
 
   // Insert a string at a specific point in the vector.  Here "baz"
   // is appended to the vector.
   strings.insert(strings.end(), "baz");
 
   // STL containers (such as vector, set, hash, etc) can be iterated
   // in a manner almost like foreach some in other languages.  First
   // an iterator must be declared.
   std::vector<std::string>::iterator iter = strings.begin();
 
   // The iterator can be used to access each element of the vector.
   for(;
       iter != strings.end(); /* Don't iterate past the end. */
       iter++) /* iters overload the increment (++) operator. */
   {
      // To retrieve the value at the index represented by the
      // iterator, some more STL syntactical sugar makes it a
      // simply matter of using the dereference (*) operator.
      std::cout << *iter;
      std::cout << std::endl;
   }
}
$ g++ vector.cpp -o vector && ./vector
foo
bar
baz
$

Let me know if I’ve made obvious mistakes, which I tend to do frequently!