简体   繁体   中英

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.

I am trying to implement a suffix trie, where I store a data structure node in a vector of nodes. 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.

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? 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 ):

23.3.6.3 vector capacity
....

 void reserve(size_type n); 

....
After reserve() , capacity() is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve() .

and

23.3.6.5 vector modifiers
....

 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 . 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. 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. A list of methods that invalidate is available here in section 'Iterator invalidation'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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