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? i.e. 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?
std::deque.push_backdoesn't invalidate references/pointers (but iterators are invalidated). en.cppreference.com/w/cpp/container/dequestd:::vector, notstd::dequethough :).push_backand doesn't invalidate references.std::dequehas its uses but is often ignored. The answers below are probably fine for this question though.