简体   繁体   English

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

[英]Using a pointer to an object stored in a vector… c++

I have a vector of myObjects in global scope.我在全局 scope 中有一个 myObjects 向量。

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?还是应该传递一个std::Vector<myObject>::iterator并增加它?

Assume for now that the vector will not get changed in the meantime.现在假设向量在此期间不会改变。

Yes - the standard guarantees in a technical correction that the storage for a vector is contiguous, so incrementing pointers into a vector will work.是的-标准在技术更正中保证向量的存储是连续的,因此将指针递增到向量中将起作用。

Yes, this will work as expected since std::vector is mandated to use contiguous storage by the Standard.是的,这将按预期工作,因为标准要求std::vector使用连续存储。 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.这几乎是 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.递增指针是合法的,当你有空间移动到下一个元素时,你可以通过递增指针来做到这一点,因为向量的缓冲区是 memory 的单个块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM