New Tutorials:   JAVASCRIPT    SASS/SCSS    PL/SQL  
See the Tutorial List

Overview of Algorithms in C++ STL

STL provide different types of algorithms that can be implemented upon any of the container with the help of iterators. Thus now we don’t have to define complex algorithm instead we just use the built in functions provided by the algorithm library in STL.

As already discussed earlier, algorithm functions provided by algorithm library works on the iterators, not on the containers. Thus one algorithm function can be used on any type of container.

Use of algorithms from STL saves time, effort, code and are very reliable.

For example, for implementing binary search in C++, we would have to write a function such as:

bool binary_search( int l , int r , int key ,int a[])
    if(l > r)
        return -1;
        int mid=(l+r)/2;
        if(a[mid] == key) 
            return true;
        else if(a[mid] > key) 
            return binary_search(l, mid-1, key, a);
        else if(a[mid] < key) 
            return binary_search(mid+1, r, key, a);

Note that the above function will work only if the array is of intergers and characters.

But in STL we can just use the binary_search() provided by the algorithm library to perform binary search. It is already defined in the library as :

return binary_search(a, a+a.size())

Plus the above function will work on any type of container.

Types of Algorithms in Algorithm Library

  1. Sorting Algorithms
  2. Search algorithms
  3. Non modifying algorithms
  4. Modifying algorithms
  5. Numeric algorithms
  6. Minimum and Maximum operations.