C ++ vector <char> and sockets

Is there a way to call send / return to a vector?

What would be good practice for buffering socket data in C ++? For example: read to \ r \ n or to upper_limit (4096 bytes)

+4
source share
3 answers
std::vector<char> b(100); send(z,&b[0],b.size(),0); 

Edit: I'm second to Ben Haymers and me22 . Also see this answer for a general implementation that is not trying to access the first element in empty vectors.

+10
source

To expand on what sbi said, std :: vector is guaranteed to have the same memory format as the C-style array. Thus, you can use & myVector [0], the address of the 0th element, as the address of the beginning of the array, and you can safely use the elements myVector.size () of this array. Remember that they are both invalidated as soon as you then modify the vector!

+6
source

One thing to consider: & v [0] is technically not allowed if the vector is empty, and some implementations will claim for you, so if you get buffers from others, make sure they are not empty using this trick.

C ++ 0x vector has a .data () member function (e.g. std :: string) to avoid this problem and make everything more understandable.

+6
source

All Articles