Sharing! What gained.

Jul 25, 2015

Getting Started with Boost C++ Library




Boost library is a C++ library which contain 80+ library to play with. Boost library is licensed under Boost Software License which allows to use it in free and propietary software. Some of the Boost feature have been migrated to Standard C++ library and some are in process of migrations. It is portable and support almost every c++ compiler.

What Special does it have

  1. Multiprecision - For calculating 512+ bit integer.
  2. GIL - Image process library.
  3. Threads - No need to import separate library for threading. They also have coroutine.
  4. Regular Expression - For searching pattern in text.
  5. Any - Store any data type in it eg int, string, float, etc
  6. Asio - Networking library
  7. Lexical_cast, CRC, Metaprogramming, Lockfree structure and many more

Installing in Visual Studio

  1. Download latest version of Boost in my case it 1.58
    Visual Studio 2013 - Download 32 bit / 64 bit
    Visual Studio 2012 - Download 32 bit / 64 bit
    Visual Studio 2010 - Download 32 bit / 64 bit
    For more version click here
  2. Install package in directory C:/boost or any other directory path which doesn't contain space. 
  3. C:/boost will look like this 
  4. Open Visual Studio
  5. Create new project (Console Application) and name it Boost001 for instance.
  6. Go to Project - > Properties -> Configuration Properties -> C/C++ -> General Then add c:/boost in Additional Include Directories 

  7. Click Apply and then Ok.
  8. Write this code
    #include <iostream>
    #include <boost/any.hpp>
    
    using namespace std;
    
    int main()
    {
     boost::any tmp[4];
     tmp[0] = 10;
     tmp[1] = 3.14;
     tmp[2] = 'a';
     tmp[3] = string("Hello, World.");
    
     // With great funtionality comes great hurdle :P
     cout << boost::any_cast(tmp[0]) << endl;
     cout << boost::any_cast(tmp[1]) << endl;
     cout << boost::any_cast(tmp[2]) << endl;
     cout << boost::any_cast(tmp[3]) << endl;
    
     return 0;
    }
  9. Then compile the code 

Calculate 1024 bit with Boost

In this program, Factorial of 1000 is calculated using int1024_t data type available in Boost multprecision library.

#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>

using namespace boost::multiprecision;

int1024_t factorial(int num)
{
 int1024_t temp;

 if (num <= 1) return 1;

 temp = num * factorial(num - 1);
 return temp;
}

int main() {
 // Note: int1024_t is 1024 bit integer
 // int128_t , int512_t and many other are available.
 // http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html

 cout << "Factorial of thousand is " << factorial(1000) << endl;
}


Share this Post!

0 comments:

Post a Comment