使用指向存储在向量中的对象的指针... c++

发布于 2024-07-14 16:16:46 字数 306 浏览 4 评论 0原文

我有一个全局范围内的 myObjects 向量。

std::vector<myObject>

向方法传递一个指向向量中元素之一的指针。 此方法可以增加指针以到达下一个元素,

myObject* pmObj;

++pmObj; // the next element ??

还是应该传递一个 std::Vector::iterator 并增加它?

现在假设向量在此期间不会改变。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里梦着梦中梦 2024-07-21 16:16:46

是的 - 标准在技术修正中保证向量的存储是连续的,因此将指针递增到向量中是可行的。

Yes - the standard guarantees in a technical correction that the storage for a vector is contiguous, so incrementing pointers into a vector will work.

魂牵梦绕锁你心扉 2024-07-21 16:16:46

是的,这将按预期工作,因为标准强制要求 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.

森林迷了鹿 2024-07-21 16:16:46

如果向量没有重新分配并且你确定不会超出向量的边界,那么你可以使用这种方法。 递增指针是合法的,当您有空间移动到下一个元素时,您可以通过递增指针来实现,因为向量的缓冲区是单个内存块。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文