2

我目前正在使用向量作为 c 样式的数组来通过 Winsock 发送和接收数据。

我有一个 std::vector ,我将它用作我的“字节数组”。

问题是,我使用了两个向量,一个用于每个发送,一个用于每个接收,但我正在做的似乎相当低效。

例子:

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 只是调用 send 适当的次数,并确保一切正常。

反正。除非我在每次使用之前将向量归零,否则我会收到内容重叠的错误。有没有更有效的方法让我做我正在做的事情?因为似乎在每次调用时将整个缓冲区归零是非常低效的。

谢谢。

4

4 回答 4

1

你可以使用 m_SendBuffer.clear()

否则 end() 方法将不知道缓冲区的实际大小。

clear() 不是一个非常昂贵的调用方法。除非你正在处理一些 486 或其他东西,否则它不应该影响你的表现

于 2009-03-07T08:20:33.287 回答
1

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();
于 2009-03-11T16:06:23.087 回答
0

据我了解STL 文档,调用 clear 只是将 .end() 值设置为与 .begin() 相同并将大小设置为零,这是即时的。

它不会改变分配的内存量或内存的位置(任何迭代器显然都是无效的,但数据往往会徘徊!)。正如您已经发现的那样, .capacity() 不会改变,存储在那里的数据也不会改变。如果您总是使用 .begin() .end() 和 STL 迭代器来访问该区域,这无关紧要。

不要忘记,除非您将它们包含在初始化列表中,否则不会初始化类的方法变量。在那里添加m_SendBuffer(BUFSIZE,0)可能会奏效。

于 2009-03-11T13:42:45.927 回答
0

调用 clear 是否意味着向量的新大小为 0?如果 OP 将向量用作一大块内存,那么他们必须在 clear 后调用 resize 以确保有适当的空间可用于调用 send 和 recv。

在向量上调用 clear then resize 将与仅用零填充它大致相同,不是吗?

矢量::清除

矢量::调整大小

充满

于 2009-03-07T08:24:55.320 回答