我有以下课程:
class A {};
class B { vector<A> vect; };
Run Code Online (Sandbox Code Playgroud)
我可以像这样访问任意A:
A a = b.vect[0];
// A *a_ptr = &a;
Run Code Online (Sandbox Code Playgroud)
但是我如何才能直接进入*a_ptr?
A *a_ptr = &b.vet[0];
Run Code Online (Sandbox Code Playgroud)
编译并且不会给出运行时错误,但它指向错误的内存位置.
编辑:
我的真实世界的例子:http://ideone.com/kP8NK
当Ideone给出预期的" You are now at 0, 0, 0
"时,MS VisualStudio编译器产生" You are now at 6624656, -33686019, -1414812757
"
这不是"错误",你只是错过了差异.即:
A a = b.vect[0]; // Makes `a` a *copy* of the vector element
A *a_ptr = &a; // Address of the copy
A *a_ptr2 = &b.vect[0]; // Address of the element, not a copy
Run Code Online (Sandbox Code Playgroud)
要获得等效性,您应该将第一个更改为:
A& a = b.vect[0]; // Makes `a` a reference to the vector element
A *a_ptr = &a; // Address of the element, not a copy
Run Code Online (Sandbox Code Playgroud)
如果您在观察到这种差异后仍未达到预期效果,那么您需要向我们展示您的确切示例以及您如何确定"正确"和"错误"结果.
问题是,std::vector<>::push_back
将无效引用,指针和时元素的迭代器size() == capacity()
,因为它需要分配的内存块中.使用无效指针(等)会导致未定义的行为,因此您的结果是未知的.
您应该存储索引,并进行简单的查找以获取实际元素.(注意vector
仍然是有序的,所以即使你的房间可能在内存中移动,它们的索引也是一样的.)