Is there a way to call send / recv passing in a vector ?
What would be a good practice to buffer socket data in c++ ? For ex: read until \r\n or until an upper_bound ( 4096 bytes )
std::vector<char> b(100);
send(z,&b[0],b.size(),0);
Edit: I second Ben Hymers' and me22's comments. Also, see this answer for a generic implementation that doesn't try to access the first element in an empty vectors.
To expand on what sbi said, std::vector is guaranteed to have the same memory layout as a C-style array. So you can use &myVector[0], the address of the 0th element, as the address of the start of an array, and you can use myVector.size() elements of this array safely. Remember that those are both invalidated as soon as you next modify the vector though!
One thing to watch out for: &v[0] is technically not allowed if the vector is empty, and some implementations will assert at you, so if you get buffers from others, be sure they're not empty before using this trick.
C++0x's vector has a .data() member function (like std::string's) to avoid this problem and make things clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With