Hello everyone,
First off let me tell you what I am trying to achieve. I am trying to finish my packet class which takes in data and packs it nicely to be able to transfer it on the network.
I overload the << and >> operators to insert and extract data to and from a vector<char>. I would like to know if this is the right thing to do.
1. Should I use a vector at all or something else like char array with a fixed size etc... I was going with vector because I can re-size if needed.
2. If a vector is the best option should I use memcpy or std::copy?, I'm thinking std::copy would be better but in some cases it just messes up...
3. Is there a better way to do all is? look at the code below please.
The difference between memcpy and std::copy is that memcpy copies bytes and std::copy copies any type, including user defined types.
If you used std::copy on data in those functions, it would treat data as a uInt32, whereas memcpy is treads it as bytes (chars), that's why you need to specify the number of bytes to copy.
Further more, memcpy is a C intrinsic function (meaning it tends to be inlined), whereas std::copy is part of the C++ standard library.
Like I said though, I'm using a char vector, while that works it wouldn't really be inserting in to the vector, I would have to re-size each time, like I said in one of my questions is it better/faster to just create a big array and do operations on it?
I'm thinking std::copy would be better but in some cases it just messes up...
Out of interest, what do you mean by mess up??
so how would I copy the unsigned int etc on a char and get the same thing back?
Do you mean a char buffer? (copy an int into a char buffer??)
And...
- which platform are you currently working on?
- does your code need to work cross-platform?
- when you say "transfer it on the network", are you talking about sockets?
data does not contain the same thing that I put in on the first function...
I mean copy it to a vector<char>
I am on windows 7.
It doesn't really need to work on other platforms.
Yes I am talking about network, lets not get into Endianess though, that is a different section lol.
Yes I do use reverse too, kbw's solution is good I actually use that more often but only on raw data, containers and such tend to come back and bite you in the back when you mess with them in such a way.