Friday, August 1, 2014

Build Boost 1.55.0 C++ Libraries on Ubuntu

  Boost libraries are used by C++ programmers to increase the productivity of software product development process. Instead of reinventing the wheel, by using Boost libraries initial-development time costs are decreased remarkably.
  Boost libraries include many benefits for C++ programmers, such as shared_ptr, arrays, serialization, I/O etc. , which most of the time causes troubles. So it becomes crucial to invest time to learn Boost libraries for a C++ programmer to use these benefits and advantages.
  Most Linux distributions come with pre-installed Boost libraries. However, they do not always contain the latest version of Boost libraries.
  In order to build and start using on Ubuntu OS following steps can be followed :

1- download boost_1_55_0.zip file from
 
    http://sourceforge.net/projects/boost/files/boost/1.55.0/

2- unzip your downloaded boost_1_55_0.zip file

    $ unzip boost_1_55_0.zip

3- get required dependencies which are going to help you during build process
 
    $ sudo apt-get update
    $ sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev build-essential libbz2-dev

4- change your location into your unzipped boost_1_55_0 folder from terminal
 
    $ cd boost_1_55_0/

5- start bootstrapping

    $ ./bootstrap.sh --prefix=/usr/local

6- start building boost libraries

    $ sudo ./b2

7- after waiting for a time-period all the Boost libraries are built successfully.

    "The Boost C++ Libraries were successfully built!"

8- now Boost header files and libraries are ready for being used in your C++ applications.

Sunday, May 11, 2014

Throw and Catch Custom Exception Object in C++

Exceptions are run-time errors that occur during program execution. C++ Standard Library comes with a base class "exception" which is mainly dealing with exceptions. In some circumstances it is required to create-design your own custom exception classes in C++ as in other object oriented programming languages.
what() function of exception class of C++ Standard Library used to provide detailed information about the problem to the client program code in the case of an exception.

Following sample project created by qt creator and contains following files:
1- CustomException.pro
2- DequeWrapper.h
3- DequeWrapper.cpp
4- EmptyContainerException.h
5- EmptyContainerException.cpp
6- main.cpp

CustomException.pro file contains project configuration.

TARGET = CustomException
TEMPLATE = app
SOURCES += main.cpp \
           DequeWrapper.cpp \
           EmptyContainerException.cpp

HEADERS += \
           DequeWrapper.h \
           EmptyContainerException.h

main.cpp file contains main method and the usage of the EmptyContainerException exception instance.
#include "DequeWrapper.h"
#include <iostream>

using namespace std;
using namespace CustomContainers;

int main()
{
    try
    {
        DequeWrapper mDequeWrapper;
        mDequeWrapper.popBack();
    }
    catch(const EmptyContainerException& ex)
    {
        cerr << ex.what() << endl;
    }

    return 0;
}

DequeWrapper.h is the header file for the deque wrapper class declaration.
#ifndef DEQUEWRAPPER_H
#define DEQUEWRAPPER_H

#include <deque>
#include "EmptyContainerException.h"

namespace CustomContainers
{

class DequeWrapper
{
public:
    bool empty() const;
    int popBack();

protected:
    std::deque mDeque;
};

}
#endif // DEQUEWRAPPER_H

DequeWrapper.cpp is the implementation file for the deque wrapper header file.

#include "DequeWrapper.h"

namespace CustomContainers
{

bool DequeWrapper::empty() const
{
    return mDeque.empty();
}

int DequeWrapper::popBack()
{

    if(mDeque.empty())
        throw EmptyContainerException();

    int mItem(mDeque.back());
    mDeque.pop_back();
    return mItem;
}

}
EmptyContainerException.h file is the header file for the custom exception class declaration.
#ifndef EMPTYCONTAINEREXCEPTION_H
#define EMPTYCONTAINEREXCEPTION_H

#include <exception>

namespace CustomContainers
{

class EmptyContainerException : public std::exception
{
    public:
        virtual const char* what() const throw();
};

}

#endif // EMPTYCONTAINEREXCEPTION_H

EmptyContainerException.cpp file is the implementation file for the custom exception class header file.

#include "EmptyContainerException.h"

namespace CustomContainers
{

const char* EmptyContainerException::what() const throw()
{
    return "container is empty!";
}

}

std::exception what() method is reimplemented in the derived class EmptyContainerException to provide the description of the exception. When you run the above sample program main method following console output "container is empty" exception message is generated :


Wednesday, March 5, 2014

Binary Search Sorted Int Array Recursively

There exists a recursive solution for the binary search algorithm. At each step lower and higher bounds for the search interval are updated and the search key is scanned in this new updated interval.
For recursive binary search implementation; search interval is updated depending on the midPoint value.

midPoint = lowerBound+(higherBound-lowerBound)/2

For the starting step; lowerBound is 0 and higherBound is the last array index.

Following sample project created by qt creator and contains following files:
1- SearchIntArrayRecursively.pro
2- main.cpp


SearchIntArrayRecursively.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp

main.cpp file contains main method and recursive binarySearch function implementations.

#include <stdio.h>

int getIndexOfItemRecursively(int pSearchedItem, int* pArray, int mLowerBound, int mHigherBound)
{
    if( mLowerBound > mHigherBound )
        return -1;
    int midIndex = mLowerBound+(mHigherBound-mLowerBound)/2;

    if( pSearchedItem < pArray[midIndex] )
        return getIndexOfItemRecursively(pSearchedItem, pArray, mLowerBound, midIndex-1);
    else if(pSearchedItem>pArray[midIndex])
        return getIndexOfItemRecursively(pSearchedItem, pArray, midIndex+1, mHigherBound );
    else
        return midIndex;
}

int findIndexOfItem( int pSearchedItem, int* pArray, int pTotalItemCount )
{
    return getIndexOfItemRecursively(pSearchedItem, pArray, 0, pTotalItemCount-1);
}

int main(int argc, char* argv[])
{
    int mArray[] = {1, 2, 4, 12, 34, 45, 56, 67, 78, 89, 90};
    int mLengthOfArray = sizeof(mArray)/sizeof(int);
    printf("There are %d items in the array\n", mLengthOfArray);
    printf("Items :\n");
    for(int i = 0; i<mLengthOfArray; i++)
    {
        if( i!=mLengthOfArray-1 )
            printf("%d,", mArray[i]);
        else
            printf("%d\n", mArray[i]);
    }
    printf("Indexes :\n");
    for(int i = 0; i<mLengthOfArray; i++)
    {
        if( i!=mLengthOfArray-1 )
            printf("%d,", i);
        else
            printf("%d\n\n", i);
    }
    int mSearchItem = 12;
    int mIndex = findIndexOfItem( mSearchItem, mArray, mLengthOfArray );
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    mSearchItem = 89;
    mIndex = findIndexOfItem( mSearchItem, mArray, mLengthOfArray );
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    mSearchItem = 91;
    mIndex = findIndexOfItem( mSearchItem, mArray, mLengthOfArray );
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    return 0;
}

We can analyze the steps for the first search item 12.



Search for 12 :

  • Find midPoint. For this case midPoint is at index 5. If the searchItem (12) is less than the item at index midPoint (45) then update higherBound value with midpoint-1.
  • Search in the new range with new higherBound value. higherBound is now midPoint-1. And lowerBound is 0.
New Sub Array Shrinks To 5 Items:

  • Find midPoint. For this case midPoint is at index 2. If the searchItem is higher than the item at index midPoint then update lowerBound value with midpoint+1.
  • Search in the new range with new lowerBound value. lowerBound is now midpoint+1 and higherBound does not change for this case.
New Sub Array Shrinks To 2 Items :
  • Find midPoint. For this case midPoint is at index 3.
  • SearchedItem is not less than the item at midPoint.
  • SearchedItem is not higher than the item at midPoint.
  • Then item is at midPoint. Return index of midPoint.

When you run the above recursive binary search sample following console output is generated :