Using STL stringsteam

About stringsteam

stringsteam is a standard C++ stl library  that helps to processing string as steam. There are three types of stringsteam:

istringsteam : processing input string
ostringsteam: processing output string
stringsteam: processing both input/output steam

It’s high recommend to use stringsteam instead of sprintf because stringsteam is more safer than sprintf. Look at this code:

int n = 12345;
char szbuf[4] = {0};
sprintf(szbuf, "%d", n)

There are two potential problems in this piece of code: the format must match the covert type. Say if “%d” is “%f” or n is a float number, it crashes. If szbuf is shorter than the converted result, it crashes because sprintf doesn’t check the buffer length before it copies, so the buffer overflows. (sprintf_s would be more safer where it requires a buffer size as an argument in function if you really want to use sprintf to format a string).

There is no such crash when using stringsteam. compiler knows what type it is of n so it will automatically convert n as %d when it is a integer or %f when it is a float. The stream is dynamic so you don’t need to worry about memory overflow when it copies string.

how to use stringsteam

string res = "10000";
int n = 0;
steam<<res;       //steam now is 10000;
steam>>n;         //n is 1000 now

Following is a code example to use stringsteam for tree serialization and deserialization. Let’s say we have a binary tree like the following graph:

  1
 / \                serialization string: [1,2,3]
2   3

 1
 \
  2                 serialization string: [1,null,2,3]
 /
3

For tree [1,2,3] serialization, uses ostringsteam:

serialize

the output string return:”1 2 # # 3 # #”

Then use “1 2 # # 3 # #” as input argument to deserialize a  tree:

deserialize

Advertisements

Sparse Matrix Multiplication

Sparse Matrix is a special matrix that most elements are zero. While processing sparse matrix in computer, to save space and running time, we only need to store those nonzero elements into a two dimension array.

 A = | 1 0 0|          | 7 0 0|  
     |-1 0 3|      B = | 0 0 0|
                       | 0 0 1|

      | 1 0 0|    |7 0 0|   | 7 0 0|
AXB = |-1 0 3| X  |0 0 0| = |-7 0 3| 
                  |0 0 1|

For A, it represents by a sequential array that for each row,only have the nonzero pair value that contains column and value:

A = [[0,1],              row 0, column 0 has value 1,
     [0,-1],[2,3]]       row 1, column 0 is -1, column is 3

Then multiply this dense vectors