Home > OS >  How to convert a vector to a string without taking up more space ?
How to convert a vector to a string without taking up more space ?

Time:12-06

std::vector<uchar> bitstream;

stringstream ss;
copy(bitstream.begin(),bitstream.end(),ostream_iterator<int>(ss," "));
    
string bitstream_string ;
 bitstream_string=ss.str();

Every element in the vector is a number 0-255, and after turning into a string, it takes up about 4 times more space, and I wonder why

I wonder converting a vector to a sting without taking up more space


The reason I wanted to turn the vector into a string was that I tried to compress the vector using an API from ZSTD (a new lossless compression algorithm that Facebook open-sourced), but I found that the contents of the vector were different after compression and decompression. Because there was a demo that used ZSTD to compress strings, I tried to turn the vector into a string and then compress it, and found that it could be compressed 2.6 times, but the byte used was actually larger, because the string itself is about 200kb (vector is about 50kb).

CodePudding user response:

Two things:

  • First you have to account for the space you add between the numbers. That alone will guarantee at least double (almost) the length of the string.

  • Secondly, std::ostream_iterator uses the text-only operator << to insert into the stream. That means all numbers will use one or more characters in the output string. For example the number 123 will use three characters in the output.

These two together will easily explain that the string length is much longer than the vector lenght.

If you want a string with text, there's no way to work around it being longer than the raw binary data of the vector.

  •  Tags:  
  • c
  • Related