Monday, March 19, 2012

What is STL in C++?

The Standard Template Library or simply STL is a container classes, algorithms and iterators of the C++ library. A container is object which contains the collection of the objects. These are implemented as a template classes. Before going into STL, better get the knowledge of Template classes in C++. The STL's are classified into following groups.

Container Classes:

1. Sequence Containers:
  • Vector: This is like dynamic array of variables, structs or objects. We can insert the data at the end. we can access the data using indexing.  see the example below.
  • De queue: Similar to array, and we can insert the data at the beginning and end. In this also we can access the data using indexing.
  • List: Similar to linked list. We can add/delete the data from anywhere.
2. Container Adaptors:
  • Stack: Same as Stack data structure. It uses LIFO concept.
  • Queue: Same as queue data structure. It uses FIFO concept.
  • Priority queue: Is a special adopter container, which contains the elements such a way that first element of the container is always greater.
3. Associative Adaptors:
  • Set : is a collection of ordered data in a balanced binary tree structure. And duplicate values are not allowed in SET
  • Multi Set: Same as SET, except duplicate values are allowed.
  • Map: is a collection of associated key-value pair in a balanced binary tree structure. And duplicate keys are not allowed.
  • Multi Map: Same as Map except, duplicate keys are allowed in multi-maps.

  Operations/Utilities on STL:

  •  Iterator:  This is used identify the elements in STL using position. This is also used to access the elements in the STL.
  • Algorithm: This is used to apply the function like find, sort, count, search on STL.
  • Auto_ptr: This is used for avoiding memory leaks. Using this , we can allocate the memory and no need of freeing the memory. auto_ptr will delete the allocated memory automatically after its use.

Vector Example:

using namespace std;

// need to include corresponding STL header file. e.g vector file for vector STL
    vector<int> v; // declaring the vector STL. similar to template
    for (int i =0;i<5;i++)
        v.push_back(10*i); // adding the element at the end

    vector<int>::iterator ii; // declaring the iterator
        cout<<*ii<<" "; // accessing the value using iterator

0 10 20 30 40

Stack Example:

using namespace std;


    stack<int> st; // declaring stack STL
    for (int j=0;j<5;j++)
        st.push(j*10); // pushing the element into the stack
    while(!st.empty())   // checking for empty stack
        cout<<" "<<;   // getting the top of the stack element
        st.pop();    // deleting the element from the stack
40 30 20 10 0

No comments:

Popular Posts