简体   繁体   English

矢量和指针

[英]Vectors and Pointers

The main issue with vectors and pointers to their elements is that they can be reallocated in memory whenever a push_back is called, rendering the pointer invalid. 向量和指向其元素的指针的主要问题是,无论何时调用push_back ,它们都可以在内存中重新分配,从而使指针无效。

I am trying to implement a suffix trie, where I store a data structure node in a vector of nodes. 我正在尝试实现后缀trie,其中我将数据结构node存储在node向量中。 I know that for a string of size n the number n(n+1)/2 is an upperbound for the number of nodes in the trie. 我知道对于大小为n的字符串,数字n(n + 1)/ 2是trie中节点数的上限。

So will the code 代码也是如此

std::string T = "Hello StackOverflow!";
std::vector<Node> nodes;

int n = T.length();
nodes.reserve(n*(n+1)/2);

guarantee that any pointers I create referring to elements of nodes will not be invalidated? 保证我创建的任何指向nodes元素的指针都不会失效? ie will this guarantee that the vector is not reallocated? 即这会保证向量不被重新分配吗?


Edit : I've implemented this and I keep getting the following error at runtime. 编辑 :我已经实现了这一点,并在运行时不断收到以下错误。

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::at: __n (which is 0) >= this->size() (which is 0)
Aborted (core dumped)

Any ideas what could be causing this? 可能导致这种情况的任何想法?

According to the standard ( N4140 ): 根据标准( N4140 ):

23.3.6.3 vector capacity 23.3.6.3载体容量
.... ....

 void reserve(size_type n); 

.... ....
After reserve() , capacity() is greater or equal to the argument of reserve if reallocation happens; reserve() ,如果重新分配, capacity()大于或等于reserve的参数; and equal to the previous value of capacity() otherwise. 并且等于capacity()的先前值。 Reallocation happens at this point if and only if the current capacity is less than the argument of reserve() . 当且仅当当前容量小于reserve()的参数时,才会发生重新分配。

and

23.3.6.5 vector modifiers 23.3.6.5向量修饰符
.... ....

 void push_back(const T& x); void push_back(T&& x); 

Remarks: Causes reallocation if the new size is greater than the old capacity. 备注:如果新大小大于旧容量,则会导致重新分配。 If no reallocation happens, all the iterators and references before the insertion point remain valid. 如果没有重新分配,插入点之前的所有迭代器和引用仍然有效。

You can be certain that your pointers will not be invalidated if you are careful. 如果你小心的话,你可以确定你的指针不会失效。 See std::vector::push_back . 请参见std :: vector :: push_back It says this about invalidation : 它说这是关于失效:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. 如果new size()大于capacity(),那么所有迭代器和引用(包括过去的迭代器)都将失效。 Otherwise only the past-the-end iterator is invalidated. 否则只有过去的结束迭代器无效。

Simply make sure you do not push_back beyond capacity or call other methods that may invalidate. 只需确保不要超出容量push_back或调用可能无效的其他方法。 A list of methods that invalidate is available here in section 'Iterator invalidation'. “Iterator invalidation”部分中提供无效的方法列表。

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

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