Convert std::string to std::vector<unsigned char> and vice versa

T

timor.super

Hi group,

how to convert a string to a vector of unsigned char ?
I used to iterate trough the string to set the vector, but I think
this is not the best way to do this.
I'm a beginner with the STL

How about allocating the vector ? should I know before the size ?

And I would like to do then opposite conversion, from an unsigned char
vector to a string.
How to do this ? how about special caracters ? (\n for example)

Thanks for your help


Best regards,

N.
 
A

Alf P. Steinbach

* (e-mail address removed):
how to convert a string to a vector of unsigned char ?

std::string s = "abra kadabra";
I used to iterate trough the string to set the vector, but I think
this is not the best way to do this.
I'm a beginner with the STL

How about allocating the vector ? should I know before the size ?
Huh.


And I would like to do then opposite conversion, from an unsigned char
vector to a string.
How to do this ?

std::string t( v.begin(), v.end() );

how about special caracters ? (\n for example)

Irrelevant.
 
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

Hi group,

how to convert a string to a vector of unsigned char ?
I used to iterate trough the string to set the vector, but I think
this is not the best way to do this.
I'm a beginner with the STL

How about allocating the vector ? should I know before the size ?

If you have very large strings you can run v.reserve(s.size()) before
inserting, which might give a speed improvement. But you don't have
to.
 
T

timor.super

If you have very large strings you can run v.reserve(s.size()) before
inserting, which might give a speed improvement. But you don't have
to.


Thanks both for your answer, that solves my problem :)

Best regards,

N.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top