title: Serialization/Deserialization of a Vector of Integers in C++
body: <h1>Task to be Acomplished</h1>
  
  <p>I'm trying to serialize a vector of integers into a string so that it can be stored into a file. The approach used is to copy the integers byte-by-byte into a buffer. For this I used the std::copy_n function. </p>
  
  <p>To deserialize, I've done the same thing in reverse i.e. copied byte-by-byte into an integer from the buffer and appended those integers to a vector.</p>
  
  <p>I'm not sure if this is the best/fastest way to achieve this.</p>
  
  <h1>Code</h1>
  
  <h2>Serialize function</h2>
  
  <pre><code>char *serialize(vector &lt;int&gt; nums)
  {
      char *buffer = (char *)malloc(sizeof(int)*nums.size());
      vector &lt;int&gt;::iterator i;
      int j;
      for(i = nums.begin(), j = 0; i != nums.end(); i++, j += 4) {
          copy_n(i, 4, buffer+j);
      }
      return buffer;
  }
  </code></pre>
  
  <h2>Deserialize function</h2>
  
  <pre><code>vector &lt;int&gt; deserialize(char *str, int len)
  {
      int num;
      vector &lt;int&gt; ret;
      for(int j = 0; j &lt; len; j+=4) {
          copy_n(str+j, 4, &amp;num);
          ret.push_back(num);
      }
      return ret;
  }
  </code></pre>
  
  <p>Any inputs on how I can improve this bit of code would be really helpful. I would also love to know other approaches to achieve the same.</p>