使用指向存储在向量中的对象的指针... c++
我有一个全局范围内的 myObjects 向量。
std::vector<myObject>
向方法传递一个指向向量中元素之一的指针。 此方法可以增加指针以到达下一个元素,
myObject* pmObj;
++pmObj; // the next element ??
还是应该传递一个 std::Vector
现在假设向量在此期间不会改变。
I have a vector of myObjects in global scope.
std::vector<myObject>
A method is passed a pointer to one of the elements in the vector.
Can this method increment the pointer, to get to the next element,
myObject* pmObj;
++pmObj; // the next element ??
or should it be passed an std::Vector<myObject>::iterator
and increment that instead?
Assume for now that the vector will not get changed in the meantime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的 - 标准在技术修正中保证向量的存储是连续的,因此将指针递增到向量中是可行的。
Yes - the standard guarantees in a technical correction that the storage for a vector is contiguous, so incrementing pointers into a vector will work.
是的,这将按预期工作,因为标准强制要求
std::vector
使用连续存储。 如果您正在使用一系列对象,我建议传递一对迭代器。 这几乎是 STL 使用的标准习惯用法。 这将使您的代码更加安全,因为您有一个明确的迭代端点,而不是依赖于计数或类似的东西。Yes, this will work as expected since
std::vector
is mandated to use contiguous storage by the Standard. I would suggest passing in a pair of iterators if you are working with a range of objects. This is pretty much the standard idiom as employed by the STL. This will make your code a little safer as well since you have an explicit endpoint for iteration instead of relying on a count or something like that.如果向量没有重新分配并且你确定不会超出向量的边界,那么你可以使用这种方法。 递增指针是合法的,当您有空间移动到下一个元素时,您可以通过递增指针来实现,因为向量的缓冲区是单个内存块。
If the vector is not reallocated and you're sure not to get out of vector's bounds then you can use this approach. Incrementing pointers is legal and while you have space to move to the next element you can do so by incrementing the pointer since the vector's buffer is a single block of memory.