views:

314

answers:

4

Hi, I'm currently using vectors as c-style arrays to send and recieve data through Winsock.

I have a std::vector and I'm using that as my 'byte array'.

The problem is, I'm using two vectors, one for each send, and one for each recv, but what I'm doing seems to be fairly inefficient.

Example:

std::string EndBody("\r\n.\r\n");
std::fill(m_SendBuffer.begin(),m_SendBuffer.end(),0);
std::copy(EndBody.begin(),EndBody.end(),m_SendBuffer.begin());
SendData();

SendData just calls send the appropriate amount of times and ensures everything works as it should.

Anyway. Unless I zero out the vector before each use I get errors with stuff overlapping. Is there a more efficient way for me to do what I'm doing? Because it seems that zeroing out the entire buffer on each call is horribly inefficient.

Thanks.

+1  A: 

you can use m_SendBuffer.clear()

otherwise the end() method would not know what is the real size of the buffer.

clear() is not a very expensive method to call. Unless you're working on some 486 or something it shouldn't affect your performances

Eric
A: 

Wouldn't calling clear mean the vector gets a new size of 0? If the OP is using the vector as a large chunk of memory then they'd have to then call resize after clear to ensure the appropriate space is available for calls to send and recv.

Calling clear then resize on the vector would be around the same as just filling it with zeros would it not?

vector::clear

vector::resize

fill

RaptorFactor
It won't change the memory allocation for the vector. That's normally reduced by swapping with a temporary empty vector.
David Thornley
A: 

As far as I understand the STL docs, calling clear simply sets the .end() value to be the same as .begin() and sets size to zero,which is instant.

It doesn't change the amount of memory allocated or where the memory is (any iterator will obviously be invalid, but the data tends to linger!). The .capacity() doesn't change and neither does the data stored there, as you have already discovered. If you are always using .begin() .end() and STL iterators to access the area this won't matter.

Don't forget, method variables of a class aren't initialised unless you include them in your initialisation list. Adding m_SendBuffer(BUFSIZE,0) there might do the trick.

Chris Huang-Leaver
+1  A: 

Seems like the other posters are focusing on the cost of clearing the buffer, or the size of the buffer. Yet you don't really need to clear or zero out the whole buffer, or know its size, for what you're doing. The 'errors with stuff overlapping' is a problem with SendData, that you've not posted the code for. Presumably SendData doesn't know how much of the buffer it needs to send unless the data within it is zero-terminated. if that assumption is correct, all you have to do is zero-terminate the data correctly.

std::copy(EndBody.begin(),EndBody.end(),m_SendBuffer.begin());
m_SendBuffer[EndBody.size()] = 0;
SendData();
Kylotan