简体   繁体   English

常量引用 std::vector

[英]Constant reference std::vector

How can I have a reference to a specific element in a std::vector?如何引用 std::vector 中的特定元素?

The easy way should be to store it as the index of the element (I am using a size_t variable).简单的方法应该是将其存储为元素的索引(我使用的是 size_t 变量)。

The problem I have is the possibility of inserting an element before the current, making the stored value incorrect.我遇到的问题是在当前元素之前插入元素的可能性,使存储的值不正确。

There isn't a very good way to keep track of a single element inside the vector by a pointer, reference, or index.没有一种很好的方法可以通过指针、引用或索引来跟踪vector内的单个元素。 In particular:尤其是:

  1. If you insert a new element into the vector , it may cause all outstanding references to the vector 's elements to be invalidated if an internal reallocation occurs.如果将新元素插入到vector中,如果发生内部重新分配,可能会导致对vector元素的所有未完成引用无效。 Insertions can happen either by calling insert , reserve , push_back , or assign (plus perhaps a few others).插入可以通过调用insertreservepush_backassign (可能还有其他一些)来发生。 This could cause the reference to refer to an invalid object, resulting in undefined behavior if the reference is used.这可能会导致引用引用无效的 object,如果使用引用会导致未定义的行为。

  2. If you remove an element from the vector , then the reference may no longer point at the same element.如果从vector中删除一个元素,则引用可能不再指向同一个元素。 Accessing the reference may result in you referring to the wrong object.访问参考可能会导致您引用错误的 object。

If you really must hold a reference to an element in a vector , one option would be to have the vector store (smart) pointers to objects instead of the objects themselves.如果您确实必须在vector中保存对元素的引用,则一种选择是让vector存储(智能)指向对象的指针,而不是对象本身。 That way, you can store a copy of that pointer elsewhere and no matter what happens in the vector , the pointer should still be valid.这样,您可以将该指针的副本存储在其他地方,并且无论vector中发生什么,该指针都应该仍然有效。 This is really the Fundamental Theorem of Software Engineering in practice - adding another layer of indirection can solve most problems.这确实是实践中软件工程的基本定理——添加另一层间接可以解决大多数问题。

The only reliable solution is to have your vector be a vector of pointers and just remember your pointer.唯一可靠的解决方案是让你的向量成为一个指针向量并记住你的指针。

Otherwise you can't maintain a reference because, as you mentioned, the vector might move elements around.否则,您将无法维护引用,因为正如您所提到的,向量可能会移动元素。

Use a vector that contains auto pointers, ie std::vector<std::unique_ptr<YOUR_ELEMENT_TYPE>> if you are using c++0x.如果您使用的是 c++0x,请使用包含自动指针的向量,即std::vector<std::unique_ptr<YOUR_ELEMENT_TYPE>>

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

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