Dont reinvent the wheel. Use STL.

The STL (Standard Template Library) provides numerous classes and functions to simplify everyday programming tasks in C++. It is written into the C++ specification, so you needn’t worry that you may be using non-standard headers in case you do use it.

If you find yourself constantly needing stacks, queues, expandable arrays et al, the STL is just for you.

In this article, i will demonstrate the basics of the vector, which is a great replacement for an array. A vector is, simplistically speaking, an expandable array. It grows and shrinks according to your requirements.

Lets assume you need to accept N integers from the user and need to display the list at the end (a very naive example, just for demonstration).

Since N is known only at runtime, you have a problem.

  • How many locations on an array do you allocate?
  • Do you opt for the messier linked list implementation instead?

One approach is to declare an array with a large number of elements.

This approach has two disadvantages:

  • It wastes space.
  • It places an upper bound (which although may never be reached, is still a constraint) on the number of elements you can have in the array.

Without the STL, your code may look like this :


#include <iostream>
using namespace std;

int main()
{
   //Declare large array
   int arr[100];
   int size=0;

   //Get input from the user
   char reply = 'y';
   do
   {
      cout<<"Enter number : ";
      cin>>arr[size++];

      cout<<"Any more (y/n)? ";
      cin>>reply;
   } while(reply != 'n');

   //Display the list
   for(int i=0 ; i<size ; i++)
      cout<<arr[i]<<" ";

   cout<<endl;
   return 0;
}

With the STL :


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

int main()
{
   //Vector
   vector<int> V;

   //Get input from the user
   char reply = 'y';
   int num;
   do
   {
      cout<<"Enter number : ";
      cin>>num;

      //Add the number to the back of the vector
      V.push_back(num);   

      cout<<"Any more (y/n)? ";
      cin>>reply;
   } while(reply != 'n');

   //Display the list
   //Notice that the vector knows its own size
   for(int i=0 ; i<V.size() ; i++)
      cout<<V[i]<<" ";

   cout<<endl;
   return 0;
}

Line 8 creates the vector. The datatype is specified within <>. So in case you want to create a vector that holds chars, then you would type

vector<char> V;

The number of elements in the vector can be found using the size() function. This simplifies things a lot. You no longer have to maintain and update separate variable that indicates the size.

Accessing an element in a vector can be done similar to the way in which you would access an element in an array.

There is a more efficient way to iterate through the vector, but for all practical purposes this will do.

Good reference :
http://www.cplusplus.com/reference/stl/vector/

Leave a Reply