views:

624

answers:

3

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 )

+9  A: 
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.

sbi
+6  A: 

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!

Ben Hymers
mos
me22
+6  A: 

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.

me22