我不想使用 std::copy...这是正确的 for 循环替代方案吗?
我试图不使用STL。我的代码中有这一行:
std::copy(buffer_, buffer_ + size_ + 1, new_buffer)
如果我不想使用副本,这是正确的等效项吗?
for (int i = 0; i < (size_ + 1); i++){
new_buffer[i] = buffer[i];
}
或者这是完全错误的?还是少了一位?或者其他什么?
谢谢!
i'm trying to not use STL. i have this line in my code:
std::copy(buffer_, buffer_ + size_ + 1, new_buffer)
if i want to NOT use copy, is this the right equivalent?
for (int i = 0; i < (size_ + 1); i++){
new_buffer[i] = buffer[i];
}
or is that totally wrong? or is it off by one? or something else?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,您拥有的两个代码示例将给出相同的结果。
但是,如果使用
size_ + 1
,则会出现差一错误。size_
才是正确的值,因为它已经指向最后一个元素之后的一个。Okay, the two code-samples you have will give the same result.
However, you will have an off-by-one error if you use
size_ + 1
. Justsize_
is the correct value since it already points to one past the last element.不清楚你写的是否有效。如果
buffer_
为 any 随机访问且new_buffer
为 any,则copy
版本有效输出迭代器。仅当buffer_
是指针时,您的手动版本才有效。除此之外,您的手动版本在功能上是等效的。不过,如果类型是 POD,您可能可以使用
memcpy
做得更好(需要检查重叠)。请注意,您的缓冲区(按照您编写的方式)的大小为
size_ + 1
。It's not clear whether what you wrote works. The
copy
version works ifbuffer_
is any random-access andnew_buffer
is any output iterator. Your manual version only works ifbuffer_
is a pointer.Other than that, your manual version is functionally equivalent. If the types are POD, though, you could probably do better with
memcpy
(subject to checking for overlaps).Note that your buffer, the way you wrote it, has size
size_ + 1
.这就是我会这样做的,因为它更容易重用通用迭代器(很像 std::copy),因为特定于迭代器类型(随机访问)的代码位于循环之外:
所以你不会如果您决定使用其他类型的迭代器,则必须更改循环。
一些代码检查实用程序可能会抱怨这一点,因为他们认为您将发生访问冲突,但事实并非如此,因为最后一次取消引用发生在最后一次递增之前。
顺便说一句,变量名的大小的选择有点令人困惑。这意味着
buffer + size
将超过buffer
的末尾,因为您开始将数组元素标记为零,但开始对它们进行计数,因此最后一个元素通常位于索引size - 1
处。另外,如果您要使用 for 循环和索引运算符,则应该使用
unsigned int
进行索引。负指数是合法的,但我认为你不打算允许它们在这里。This is how I would do it, since it's easier to reuse with general iterators (much like std::copy), because the code that is specific to the iterator type (random access) is outside of the loop:
So you wouldn't have to change the loop if you decided to use some other type of iterator.
Some code checking utilities might complain about this because they think you are going to incur an access violation, but that's not the case since the last dereference happens before the last incrementing.
The choice of
size
for a variable name is kind of confusing here, BTW. It implies thatbuffer + size
would be one past the end ofbuffer
, since you start labeling elements of an array at zero, but you start counting them at one, so the last element will be at indexsize - 1
typically.Also, if you are going to use a for loop and the indexing operator you should use an
unsigned int
to index. Negative indices are legal, but I don't think you intend to allow them here.