Saturday, 4 January 2014

Stringstream,Sprintf,next_permutation

Many Time we need to convert the number to string.
So I bring you methods where you can convert the number to string.

Lets us declare enumeration function that tell whether it's Integer or Float value.

enum Type
{
    INT,FLOAT
};
In C++
string convert2string(void *value,int type)
{
 stringstream convertor;
 string result;
 switch(type)
 {
  case INT:
    convertor<<*static_cast<int*>(value);
                  break;
  case FLOAT:
    convertor<<*static_cast<float*>(value);
                                break;
 }
 convertor>>result;
 return result;

}
In C
string convert2stringc(void *value,int type)
{
  char buffer[80];
  switch(type)
  {
   case INT:
    sprintf(buffer,"%d",*(int*)value);
    break;
   case FLOAT:
    sprintf(buffer,"%f",*(float*)value);
    break;
  }
  return buffer; 
}

Next Permutation is very useful which generates all the permutation of the given vector
sort(container.begin(),container.end());
do
{
  //Do all the operation here 
}next_permutation(container.begin(),container.end());

No comments:

Post a Comment