Archived

This topic is now archived and is closed to further replies.

STL vector question

This topic is 5309 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can you do a memcpy type functionality with a STL vector? Take for example you have 100 bytes (with embedded nulls) that you want to memcpy from a vector into a struct... Or memcpy the struct into the vector. Take for example:

      vector<char> message;

      memcpy(&message[0], "1234\06789", 10);

I want to put those 10 bytes into the vector. Then later on I want to copy whats in that vector and copy into a char[100] buffer. I know string is setup prefectly for what i want to do, but that doesn''t seem to handle embedded nulls...

Share this post


Link to post
Share on other sites
std::string handles embedded nulls just fine, and will convert to a vector for you.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
First, resize the vector so it has enough space to hold your string.

message.resize(10);

Then I prefer to use std::copy instead of memcpy. std::copy is in the algorithm header.

char *msg = "1234\06789";
std::copy(msg, msg+10, message.begin());


And std::string can handle null characters in the middle of the string.

Share this post


Link to post
Share on other sites
Whoa nelly! Abusing STL like that does give me physical pain

Seriously, what exactly are you trying to do? You can''t use a vector like an array. Even if it is implemented like that (most of the time it is, but...), using it like that is really bad programming because it relies on underlying implementation and breaks encapsulation. A vector is supposed to be a collection of objects, not a region of continuous memory.

If you want to copy something from a vector to another STL container you can use copy
copy(message.begin(), message.end(), other_container.begin());
To do something else you''d probably write a loop like
for(vector::const_iterator character = message.begin(); charachter != message.end(); ++character)
{
some_buffer += character; // ? or something?
}

You can also replace all the nulls in your strings by a special character (there are STL algorithms for this too, easy), and then use string instead.

Share this post


Link to post
Share on other sites
quote:
Original post by Jedyte You can also replace all the nulls in your strings by a special character (there are STL algorithms for this too, easy), and then use string instead.
No need to do that. STL string handles embedded nulls.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites