Re: How to turn vector to an address
Jack wrote:
Hi,
Here is the code snippet, don't mind its correctness, just take it as
an example
struct
{
...
} FRUIT, *PFRUIT;
struct
{
std::vector<FRUIT> fruitarr;
};
============================
I have an address comparison...
pos = a - fruitarr; (a is PFRUIT, b4 modification fruitarr was also
of type PFRUIT)
============================
And the subtraction worked very well until I changed that line to
std::vector
The statement pos = a - fruitarr; did not work any more (compile-time
error) My question is how do I get the address from the vector<FRUIT>
object?
FRUIT is a variable, not a type. Use
struct FRUIT
{
// ...
};
typedef FRUIT* PFRUIT;
Now, as to the subtraction, What exactly are you trying to do? The address
of the vector itself is probably not of interest to you - rather, I would
imagine that you want an address that points "inside" the vector. Such
pointers can be taken, but you have to use care, because the vector may
automatically resize itself, thus invalidating your pointers (the conditions
underwhich resize will occur are well-defined, so care is sufficient - no
luck required).
std::vector<FRUIT> fruitarr;
// ... put stuff into fruitarr
PFRUIT a = ... some expression
std::ptrdiff_t = a - &*fruitarr.begin();
The above is valid ONLY if a actually points to an element of fruitarr. If
fruitarr is resized, a becomes invalid, and comparing it to begin() becomes
undefined.
Generally, when using std::vector, you should iterate through and
dereference into the vectors contents using std::vector<T>::iterator instead
of T*:
std::vector<FRUIT> fruitarr;
// ... put stuff into fruitarr
std::vector<FRUIT>::iterator a = ... some expression
std:::ptrdiff+t pos = a - fruitarr.begin();
The same invalidation rules apply though - if fruitarr is resized, a becomes
invalid.
-cd