at a time, I created a pointer point to a std::vector
, then I did some push_back
, reserve
, resize
operation to that vector, after such operations, is it safe to compare the pointer to the address of that vector to check whether the pointer point to that vector, because there might be some re-allocation of memory.
for example
std::vector<int> vec;
vector<int>* pVec = &vec;
vec.reserve(10000);
assert(pVec == &vec);
vec = anotherVec;
assert(pVec == &vec);
what is more, is it safe to compare a pointer to the first value of vector? for example:
std::vector<int> vec(1,0);
int* p = &vec[0];
// some operation here
assert(p == &vec[0]);
As I tested by myself, it seems that the first situation is safe, while the second is not, but I can't be sure.
The C++ function std::vector::operatorvector::operatorA vector operator is a differential operator used in vector calculus. Vector operators are defined in terms of del, and include the gradient, divergence, and curl: Vector operators must always come right before the scalar field or vector field on which they operate, in order to produce a result.https://en.wikipedia.org › wiki › Vector_operatorVector operator - Wikipedia== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.
We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can't be multiplied or divided.
In case of vectors, the operator “==” is overloaded to find the result quickly.
If you're comparing the pointers themselves then you can just use operator== on the whole vector (of vectors). What it does is first checks if the sizes of the two vectors are equal. If they are, it subsequently compares each element using operator== .
std::vector<int> vec;
vector<int>* pVec = &vec;
vec.reserve(10000);
assert(pVec == &vec);
is safe.
std::vector<int> vec(1,0);
int* p = &vec[0];
// some operation here
assert(p == &vec[0]);
is not safe.
The first block is safe since the address vec
will not change even when its contents change.
The second block is not safe since the address of vec[0]
may change; for example when the vec
resizes itself — e.g, when you push_back elements to it.
it seems that the first situation is safe, while the second is not
That's right. In the first "situation", the vec
object itself stays wherever it is in memory regardless of the reserve
call, which might move the managed elements to another area of dynamic memory. It's because elements can be moved that the pointers may not compare equal in the second scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With