I have the following classes:
class A {};
class B { vector<A> vect; };
I can access an arbitrary A like this:
A a = b.vect[0];
// A *a_ptr = &a;
But how can I get directly to *a_ptr?
A *a_ptr = &b.vet[0];
compiles and doesn’t give runtime errors, but it points to a wrong memory location.
EDIT:
my real world example: http://ideone.com/kP8NK
While Ideone gives the expected “You are now at 0, 0, 0“, MS VisualStudio compiler yields “You are now at 6624656, -33686019, -1414812757“
It’s not “wrong”, you just missed the difference. Namely:
To get the equivalence, you should change your first one to:
If you’re still not getting what you expect after observing this difference, then you’ll need to show us your exact example along with how you’re determining what “right” and “wrong” outcomes are.
The problem is that
std::vector<>::push_backwill invalidate references, pointers, and iterators to elements whensize() == capacity(), because it needs to allocate a new chunk of memory. Using an invalidated pointer (et al.) leads to undefined behavior, so your results are unknown.You should store indices instead, and do a trivial look-up to get the actual element. (Note
vectorremains ordered, so even though your rooms may move in memory, their index is the same.)