Saturday, July 28, 2012

My experience on C++ Serialization Solutions

Recently I tried 3 solutions for serializing request data in my Apache filter module in C++:
1- Google Protocol Buffer
2- boost serialization
3- msgpack
I was disappointed of using solutions 1 and 2 because of errors I faced. I submitted errors in many forums and related mailing lists, but I couldn't get any answer.
Google protocol buffer seems professional but It needs classes to be defined in specific way which that protocol forces.
BTW I started with this solution and designed *.protoc files and generated my model files.
the solutions worked fine in a console application but I've got segmentation fault in Apache module without any specific error. ( I tried debugging with gdb, ddd,.... but no chance to resolve the error).
So I switched to boost serialization. It was much simpler than Google solution but It didn't work completely.
It worked fine in console application and Apache filter too.
but I've segfault when I tried to serialize nested classes.
I returned to my mind, searching a solution recommended by one of my friends( Kamyar, which has been used that solution in .NET).
It was msgpack, the 3rd solution.
It's much simple than Google solution and even simpler than boost serialization.
It worked fine without any headache. As msgpack website says, It's much fast from Google and boost solution :
http://www.msgpack.org

Friday, July 27, 2012

How to run class member function in C++11 thread


class X
{
private:
 int mX;
public:
 F()
 {
   // some work
 }
};

void thread_sample()
{
  X x;
  std::thread th(&X::F,&x);
  th.join(); // call detach() if you want this method not to wait for F() to finish
 }

Tuesday, July 17, 2012

Simplest threading sample in C++11

If you were looking for multitasking and threading library in C++.
C++11 standard brought multitasking for you in the best way.
Here is the simplest threading sample in C++11. I'll post more advanced samples progressively.
I've tested this code sample in VS2012 RC(It's free for download).
#include <thread>
#include <iostream>
void hello()
{
 std::cout << "hello multitasking world!";
}
int main(int argc, char* argv[])
{
 std::thread tr(hello);
 tr.join();
 getchar();
 return 0;
}




"Execute Around Sequence", C++ Pattern

For clearing the need for this pattern, I start this post with a problem statement.
Problem:
"suppose that we have a pair of actions that surrounds a sequence of  statements and we need abstract that actions around the statements and have a error prone and exception safe code".
Let's start with a sample code snippet :
void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
  
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

  |---------------------------------------------------------------------------------------------------------|
   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|


}
    ---------------- Code 1 -----------------------
What happens in "Code 1" if an exception occur in block 2?. Answer is easy; block 3 won't run! So acquired lock will not be unlocked and other threads will waiting for unlock forever, allocated memory in part 1 won't be freed and all resources acquired in part1 won't be released.
Solution:
Initial solution which may bloom in your mind may be following strategy :

void F()
{
  |----------------------------------------------------------------------------------------------------------|

  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try

{
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|
} catch(...)
{
  throw ;
}
finally
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}
}

    ---------------- Code 2-----------------------
But as you know, C++ doesn't have finally statement in exception handling. So we have to change the code as following :


void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try
{

  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

} catch(...)
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

  throw ;
}

  |---------------------------------------------------------------------------------------------------------|
   |3'. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}

    ---------------- Code 3-----------------------
Code 3 is an acceptable solution but how about the case you are not allowed to use try/catch ?
Considering this fact that destructor of C++ class will run automatically if object goes out of scope, guides us to write a class and put "block 1" of Code 1 into a constructor of class and "block 3" of Code 1 into destructor of that class. This way helps us to achieve an exception safe code which is named executive around sequence :

class scoped_resource_manager
{
public:
  scoped_resource_manager(resource_related_parameters)
{
     block 1 : acquires lock,allocate memory, open connections ....
}
~scoped_resource_manager()
{
     block 3 :  release lock, free memory , close  connection ...
}

}

void F()
{
 scoped_resource_manager resource_manager(resource_related_parameters);
  |----------------------------------------------------------------------------------------------------|

  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

}

    ---------------- Code 4-----------------------
In Code 4, we are not worry if exception occurs in block 2 or not; all allocated resources will be released  when function returns or execution steps out of it's scope because of automatically running  of scoped_resource_manager class destructor.!

Thanks for C++ class destructors.
"Finally" here is a simple real world code sample for you :
 class ScopedConnection
{
 private :
  BaseDBProvider *mDB;
 public:
  ScopedConnection(BaseDBProvider *pDB)
  {
   mDB=pDB;
   mDB->Open();
                       mDB->StartTransaction();
                }
  ~ScopedConnection()
  {
                        mDB->DetachTransaction();
                  mDB->Close();
  }
};
void F()
{
 BaseDBProvider *bdp=DBFactory::GetDBProvider();
 ScopedConnection scoped_con(bdp);
 DBDataReader *dr;
 dr=bdp->ExcecuteReader(dbs);
 while(dr->ReadNext())
  ret->push_back(Load(dr));
 return ret;
}

scoped_ptr<T> and scoped_lock ( from boost library ) are also implemented to help us in such problems.

Sunday, July 1, 2012

Decompose text to valid words (Word breaking)

Given a dictionary of valid words and an input text, write a function to check if the input text can be decomposed into valid words from dictionary.
Hint 1: use dynamic programming technique.
Hint 2: define T[k] is true if text[0...k] can be decomposed into valid words
Hint 3: T[k] is true if there exists any j : 0..k-1 where T[j] is true and text[j..k] is a valid word in dictionary.
This hints help us to write a simple loop to get the answer.


static string dic[4]={"bed","bath","beyond","and"};

bool decomps(string txt)
{
 map<string,bool> dm;
 for(int i=0;i<4;i++)
  dm[dic[i]]=true;
 vector<bool> t(txt.size()+1,false);
 t[0]=true;
 for(int k=1;k<=txt.size();k++)
 {
  bool candecomp=false;
  for(int i=0;i<k;i++)
  {
   string srch=txt.substr(i,k-i);
   map<string,bool>::iterator f=dm.find(srch);
   if(t[i]==true && f!=dm.end())
   {
    t[k]=true;
    break;
   }
  }
 }
 return t[txt.size()];
}
void  test_decomp()
{
 cout << decomps("bedbathandbeyond");
}

Saturday, June 23, 2012

Visitor design pattern sample in C++


Visitor design pattern represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Using visitor you put all operations to be performed on various elements of an object to a single separate class names "Visitor".

Here I'm publishing a sample code to demonstrate how to use this design pattern to in marketing solution.
Here we have a portfolio of products ( portfolio has many elements/products ) and every product has a method named "Accept" which accepts a visitor and calls it's Visit(..) function by sending itself as argument to it.
Please see following code for more detailed information :
----------------------
#ifndef _VISITOR_H
#define _VISITOR_H
#include <string>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>
using namespace std;
class Tableau;
class KaraPhone;
class  ProductPortfo;
class ProductBase;
class ProductVisitor
{
public:
 virtual void Visit(Tableau* )=0;
 virtual void Visit(KaraPhone* )=0;
 virtual void Visit(ProductPortfo* )=0;
};
class ProductBase
{
public:
 virtual void Accept(class ProductVisitor* )=0;
 string Name;
};
class Tableau:public ProductBase
{
private:
 Tableau(){}
public :
 Tableau(string pName){Name=pName;}
 void Accept(ProductVisitor* pVisitor)
 {
  pVisitor->Visit(this);
 }
 
};
class KaraPhone:public ProductBase
{
private:
 KaraPhone(){}
public :
 KaraPhone(string pName){Name=pName;}
 void Accept(ProductVisitor* pVisitor)
 {
  pVisitor->Visit(this);
 }
};
class ProductPortfo:public ProductBase
{
public:
 ProductBase *mProducts[2];
 
public:
 ProductPortfo()
 {
  mProducts[0]= new Tableau("tableau7");
  mProducts[1]= new KaraPhone("Karaphonev1");
  Name="Products Portfo";
 }
 
 void Accept(ProductVisitor *pVisitor)
 {
  for(int i=0;i<sizeof(mProducts)/sizeof(mProducts[0]);i++)
   mProducts[i]->Accept(pVisitor);
  pVisitor->Visit(this);
 }
};
class PresentorVisitor:public ProductVisitor
{
public :
 void Visit(Tableau *pTableau)
 {
  cout << "PRESENT: best BI solution is " << pTableau->Name;
 }
 void Visit(KaraPhone *pKaraPhone)
 {
  cout << "PRESENT: Karaphone helps you to enefit :" << pKaraPhone->Name;
 }
 void Visit(ProductPortfo *pProd)
 {
  cout << "PRESE tell about company products " << pProd->Name;
 }
};
class POCVisitor:public ProductVisitor
{
public :
 void Visit(Tableau *pTableau)
 {
  cout << " POC: this dashboard is made by " << pTableau->Name;
 }
 void Visit(KaraPhone *pKaraPhone)
 {
  cout << "POC: this benefit is after running this :" << pKaraPhone->Name;
 }
 void Visit(ProductPortfo *pProd)
 {
  cout << "Give  CD of demo softwares :" << pProd->Name;
 }
};

#endif


Friday, June 15, 2012

Rain water trap problem 2D version


Given a 2D matrix where each element represents the elevation(height) on that point, find how many rain water it is able to hold.(Twitter interview question)
For example, given the below 3×3 matrix:
3 3 3
3 0 3
3 3 3
It should hold 3 units of rain water.
I wrote a code for that and I think It works. I tested it against various inputs and got right answer. Please let me know if something appears wrong.
here is my code :

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

vector<vector<int> > Visited;
int HowMuchCanHold(vector<vector<int> > &M,int i,int j)
{
 Visited[i][j]=1;
 if(i==0 || j==0 || i==M.size()-1 || j==M[0].size()-1) // we are in borders
  return -1; // drops to earth
 int up=M[i-1][j],down=M[i+1][j],left=M[i][j-1],right=M[i][j+1];
 int minall=1<<10;
 if(!Visited[i-1][j])
  minall=min(minall,up);
 if(!Visited[i+1][j])
  minall=min(minall,down);
 if(!Visited[i][j-1])
  minall=min(minall,left);
 if(!Visited[i][j+1])
  minall=min(minall,right);
 
 int mij=M[i][j];
 if(minall>mij)
  return minall-mij;
 else
  if(minall<mij)
   return -1; // can't hold the drop
 
 int minup=1<<10,mindown=1<<10,minleft=1<<10,minright=1<<10;
 if(mij==up && Visited[i-1][j]==0) // drop may flow up
  minup=HowMuchCanHold(M,i-1,j);
 else
  if(mij!=up)
   minup=up-mij;
 if(mij==down && Visited[i+1][j]==0) // drop may flow down
  mindown=HowMuchCanHold(M,i+1,j);
 else
  if(mij!=down)
   mindown=down-mij;
 if(mij==left && Visited[i][j-1]==0) // drop may flow left
  minleft=HowMuchCanHold(M,i,j-1);
 else
  if(mij!=left)
   minleft=left-mij;
 if(mij==right && Visited[i][j+1]==0) // drop may flow right
  minright=HowMuchCanHold(M,i,j+1);
 else
  if(mij!=right)
   minright=right-mij;
 if(minup<0 || mindown<0 || minleft<0 || minright <0) // drop wil fall from up,down,left or right!
  return -1; // can't hold the drop
  int min1=min(minup,mindown);
  int min2=min(minleft,minright);
  minall=min(min1,min2);
  return minall;
}
int DropTo(vector<vector<int> > &M,int i,int j)
{
  Visited=vector<vector<int> >(M.size(), vector<int>(M[0].size(),0));
  return HowMuchCanHold(M,i,j);
}
int get_watr_trap(vector<vector<int> > M)
{
 int row=M.size();
 int col=M[0].size();
 int total=0;
 int nexthold=0;
 bool find=false;
 while(1)
 {
  find=false;
  for(int i=0;i<row;i++)
  {
   for(int j=0;j<col;j++)
   {
    nexthold=DropTo(M,i,j);
    if(nexthold>0)
    {
     find=true;
     M[i][j]+=nexthold;//fill current cell up to the maxhold
     total+=nexthold;
    }
   }
  }
  if(!find)
   break;
 }
 return total;
}
void test_water_trap()
{
 vector<vector<int> > M(4, vector<int>(4,10));
 M[1][1]=0;
 M[1][2]=2;
 M[2][1]=4;
 M[2][2]=8;
 M[3][0]=2;
 M[3][2]=8;
 int water_trapped=get_watr_trap(M);
 cout << water_trapped << endl;
}


Saturday, July 28, 2012

My experience on C++ Serialization Solutions

Recently I tried 3 solutions for serializing request data in my Apache filter module in C++:
1- Google Protocol Buffer
2- boost serialization
3- msgpack
I was disappointed of using solutions 1 and 2 because of errors I faced. I submitted errors in many forums and related mailing lists, but I couldn't get any answer.
Google protocol buffer seems professional but It needs classes to be defined in specific way which that protocol forces.
BTW I started with this solution and designed *.protoc files and generated my model files.
the solutions worked fine in a console application but I've got segmentation fault in Apache module without any specific error. ( I tried debugging with gdb, ddd,.... but no chance to resolve the error).
So I switched to boost serialization. It was much simpler than Google solution but It didn't work completely.
It worked fine in console application and Apache filter too.
but I've segfault when I tried to serialize nested classes.
I returned to my mind, searching a solution recommended by one of my friends( Kamyar, which has been used that solution in .NET).
It was msgpack, the 3rd solution.
It's much simple than Google solution and even simpler than boost serialization.
It worked fine without any headache. As msgpack website says, It's much fast from Google and boost solution :
http://www.msgpack.org

Friday, July 27, 2012

How to run class member function in C++11 thread


class X
{
private:
 int mX;
public:
 F()
 {
   // some work
 }
};

void thread_sample()
{
  X x;
  std::thread th(&X::F,&x);
  th.join(); // call detach() if you want this method not to wait for F() to finish
 }

Tuesday, July 17, 2012

Simplest threading sample in C++11

If you were looking for multitasking and threading library in C++.
C++11 standard brought multitasking for you in the best way.
Here is the simplest threading sample in C++11. I'll post more advanced samples progressively.
I've tested this code sample in VS2012 RC(It's free for download).
#include <thread>
#include <iostream>
void hello()
{
 std::cout << "hello multitasking world!";
}
int main(int argc, char* argv[])
{
 std::thread tr(hello);
 tr.join();
 getchar();
 return 0;
}




"Execute Around Sequence", C++ Pattern

For clearing the need for this pattern, I start this post with a problem statement.
Problem:
"suppose that we have a pair of actions that surrounds a sequence of  statements and we need abstract that actions around the statements and have a error prone and exception safe code".
Let's start with a sample code snippet :
void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
  
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

  |---------------------------------------------------------------------------------------------------------|
   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|


}
    ---------------- Code 1 -----------------------
What happens in "Code 1" if an exception occur in block 2?. Answer is easy; block 3 won't run! So acquired lock will not be unlocked and other threads will waiting for unlock forever, allocated memory in part 1 won't be freed and all resources acquired in part1 won't be released.
Solution:
Initial solution which may bloom in your mind may be following strategy :

void F()
{
  |----------------------------------------------------------------------------------------------------------|

  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try

{
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|
} catch(...)
{
  throw ;
}
finally
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}
}

    ---------------- Code 2-----------------------
But as you know, C++ doesn't have finally statement in exception handling. So we have to change the code as following :


void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try
{

  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

} catch(...)
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

  throw ;
}

  |---------------------------------------------------------------------------------------------------------|
   |3'. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}

    ---------------- Code 3-----------------------
Code 3 is an acceptable solution but how about the case you are not allowed to use try/catch ?
Considering this fact that destructor of C++ class will run automatically if object goes out of scope, guides us to write a class and put "block 1" of Code 1 into a constructor of class and "block 3" of Code 1 into destructor of that class. This way helps us to achieve an exception safe code which is named executive around sequence :

class scoped_resource_manager
{
public:
  scoped_resource_manager(resource_related_parameters)
{
     block 1 : acquires lock,allocate memory, open connections ....
}
~scoped_resource_manager()
{
     block 3 :  release lock, free memory , close  connection ...
}

}

void F()
{
 scoped_resource_manager resource_manager(resource_related_parameters);
  |----------------------------------------------------------------------------------------------------|

  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

}

    ---------------- Code 4-----------------------
In Code 4, we are not worry if exception occurs in block 2 or not; all allocated resources will be released  when function returns or execution steps out of it's scope because of automatically running  of scoped_resource_manager class destructor.!

Thanks for C++ class destructors.
"Finally" here is a simple real world code sample for you :
 class ScopedConnection
{
 private :
  BaseDBProvider *mDB;
 public:
  ScopedConnection(BaseDBProvider *pDB)
  {
   mDB=pDB;
   mDB->Open();
                       mDB->StartTransaction();
                }
  ~ScopedConnection()
  {
                        mDB->DetachTransaction();
                  mDB->Close();
  }
};
void F()
{
 BaseDBProvider *bdp=DBFactory::GetDBProvider();
 ScopedConnection scoped_con(bdp);
 DBDataReader *dr;
 dr=bdp->ExcecuteReader(dbs);
 while(dr->ReadNext())
  ret->push_back(Load(dr));
 return ret;
}

scoped_ptr<T> and scoped_lock ( from boost library ) are also implemented to help us in such problems.

Sunday, July 1, 2012

Decompose text to valid words (Word breaking)

Given a dictionary of valid words and an input text, write a function to check if the input text can be decomposed into valid words from dictionary.
Hint 1: use dynamic programming technique.
Hint 2: define T[k] is true if text[0...k] can be decomposed into valid words
Hint 3: T[k] is true if there exists any j : 0..k-1 where T[j] is true and text[j..k] is a valid word in dictionary.
This hints help us to write a simple loop to get the answer.


static string dic[4]={"bed","bath","beyond","and"};

bool decomps(string txt)
{
 map<string,bool> dm;
 for(int i=0;i<4;i++)
  dm[dic[i]]=true;
 vector<bool> t(txt.size()+1,false);
 t[0]=true;
 for(int k=1;k<=txt.size();k++)
 {
  bool candecomp=false;
  for(int i=0;i<k;i++)
  {
   string srch=txt.substr(i,k-i);
   map<string,bool>::iterator f=dm.find(srch);
   if(t[i]==true && f!=dm.end())
   {
    t[k]=true;
    break;
   }
  }
 }
 return t[txt.size()];
}
void  test_decomp()
{
 cout << decomps("bedbathandbeyond");
}

Saturday, June 23, 2012

Visitor design pattern sample in C++


Visitor design pattern represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Using visitor you put all operations to be performed on various elements of an object to a single separate class names "Visitor".

Here I'm publishing a sample code to demonstrate how to use this design pattern to in marketing solution.
Here we have a portfolio of products ( portfolio has many elements/products ) and every product has a method named "Accept" which accepts a visitor and calls it's Visit(..) function by sending itself as argument to it.
Please see following code for more detailed information :
----------------------
#ifndef _VISITOR_H
#define _VISITOR_H
#include <string>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>
using namespace std;
class Tableau;
class KaraPhone;
class  ProductPortfo;
class ProductBase;
class ProductVisitor
{
public:
 virtual void Visit(Tableau* )=0;
 virtual void Visit(KaraPhone* )=0;
 virtual void Visit(ProductPortfo* )=0;
};
class ProductBase
{
public:
 virtual void Accept(class ProductVisitor* )=0;
 string Name;
};
class Tableau:public ProductBase
{
private:
 Tableau(){}
public :
 Tableau(string pName){Name=pName;}
 void Accept(ProductVisitor* pVisitor)
 {
  pVisitor->Visit(this);
 }
 
};
class KaraPhone:public ProductBase
{
private:
 KaraPhone(){}
public :
 KaraPhone(string pName){Name=pName;}
 void Accept(ProductVisitor* pVisitor)
 {
  pVisitor->Visit(this);
 }
};
class ProductPortfo:public ProductBase
{
public:
 ProductBase *mProducts[2];
 
public:
 ProductPortfo()
 {
  mProducts[0]= new Tableau("tableau7");
  mProducts[1]= new KaraPhone("Karaphonev1");
  Name="Products Portfo";
 }
 
 void Accept(ProductVisitor *pVisitor)
 {
  for(int i=0;i<sizeof(mProducts)/sizeof(mProducts[0]);i++)
   mProducts[i]->Accept(pVisitor);
  pVisitor->Visit(this);
 }
};
class PresentorVisitor:public ProductVisitor
{
public :
 void Visit(Tableau *pTableau)
 {
  cout << "PRESENT: best BI solution is " << pTableau->Name;
 }
 void Visit(KaraPhone *pKaraPhone)
 {
  cout << "PRESENT: Karaphone helps you to enefit :" << pKaraPhone->Name;
 }
 void Visit(ProductPortfo *pProd)
 {
  cout << "PRESE tell about company products " << pProd->Name;
 }
};
class POCVisitor:public ProductVisitor
{
public :
 void Visit(Tableau *pTableau)
 {
  cout << " POC: this dashboard is made by " << pTableau->Name;
 }
 void Visit(KaraPhone *pKaraPhone)
 {
  cout << "POC: this benefit is after running this :" << pKaraPhone->Name;
 }
 void Visit(ProductPortfo *pProd)
 {
  cout << "Give  CD of demo softwares :" << pProd->Name;
 }
};

#endif


Friday, June 15, 2012

Rain water trap problem 2D version


Given a 2D matrix where each element represents the elevation(height) on that point, find how many rain water it is able to hold.(Twitter interview question)
For example, given the below 3×3 matrix:
3 3 3
3 0 3
3 3 3
It should hold 3 units of rain water.
I wrote a code for that and I think It works. I tested it against various inputs and got right answer. Please let me know if something appears wrong.
here is my code :

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

vector<vector<int> > Visited;
int HowMuchCanHold(vector<vector<int> > &M,int i,int j)
{
 Visited[i][j]=1;
 if(i==0 || j==0 || i==M.size()-1 || j==M[0].size()-1) // we are in borders
  return -1; // drops to earth
 int up=M[i-1][j],down=M[i+1][j],left=M[i][j-1],right=M[i][j+1];
 int minall=1<<10;
 if(!Visited[i-1][j])
  minall=min(minall,up);
 if(!Visited[i+1][j])
  minall=min(minall,down);
 if(!Visited[i][j-1])
  minall=min(minall,left);
 if(!Visited[i][j+1])
  minall=min(minall,right);
 
 int mij=M[i][j];
 if(minall>mij)
  return minall-mij;
 else
  if(minall<mij)
   return -1; // can't hold the drop
 
 int minup=1<<10,mindown=1<<10,minleft=1<<10,minright=1<<10;
 if(mij==up && Visited[i-1][j]==0) // drop may flow up
  minup=HowMuchCanHold(M,i-1,j);
 else
  if(mij!=up)
   minup=up-mij;
 if(mij==down && Visited[i+1][j]==0) // drop may flow down
  mindown=HowMuchCanHold(M,i+1,j);
 else
  if(mij!=down)
   mindown=down-mij;
 if(mij==left && Visited[i][j-1]==0) // drop may flow left
  minleft=HowMuchCanHold(M,i,j-1);
 else
  if(mij!=left)
   minleft=left-mij;
 if(mij==right && Visited[i][j+1]==0) // drop may flow right
  minright=HowMuchCanHold(M,i,j+1);
 else
  if(mij!=right)
   minright=right-mij;
 if(minup<0 || mindown<0 || minleft<0 || minright <0) // drop wil fall from up,down,left or right!
  return -1; // can't hold the drop
  int min1=min(minup,mindown);
  int min2=min(minleft,minright);
  minall=min(min1,min2);
  return minall;
}
int DropTo(vector<vector<int> > &M,int i,int j)
{
  Visited=vector<vector<int> >(M.size(), vector<int>(M[0].size(),0));
  return HowMuchCanHold(M,i,j);
}
int get_watr_trap(vector<vector<int> > M)
{
 int row=M.size();
 int col=M[0].size();
 int total=0;
 int nexthold=0;
 bool find=false;
 while(1)
 {
  find=false;
  for(int i=0;i<row;i++)
  {
   for(int j=0;j<col;j++)
   {
    nexthold=DropTo(M,i,j);
    if(nexthold>0)
    {
     find=true;
     M[i][j]+=nexthold;//fill current cell up to the maxhold
     total+=nexthold;
    }
   }
  }
  if(!find)
   break;
 }
 return total;
}
void test_water_trap()
{
 vector<vector<int> > M(4, vector<int>(4,10));
 M[1][1]=0;
 M[1][2]=2;
 M[2][1]=4;
 M[2][2]=8;
 M[3][0]=2;
 M[3][2]=8;
 int water_trapped=get_watr_trap(M);
 cout << water_trapped << endl;
}