Question concerning accessing vector elements, and classes

Two questions:

I'm wondering if it's possible to keep track of an element of a vector by using the elements' address. Like if the vector is constantly changing, and I can't keep track of its index. Could I have something like:

1
2
3
4
5
6
7
vector<int> myvector;

//code that fills the vector with numbers...

int *address; 

*address = &myvector[0];


Then mess around with 'address'. Code might be faulty, not sure; but the idea is still there. The only way that I see this not working is if the address of the number in the vector constantly changes or something.


Other question: If I pass a pointer to a class into a function, and that class has other variables in it (like classes, vectors, and ints), can I expect to be able to change those variables within that function and keep the changes outside the scope of that function? Might be a dumb question, but I wanted to be sure.
If you add or insert new elements then the vector is reallocated in new memory address. So in this case yout method is bad. It could br done only in case then the vector is not changed.
1: It's better to do any "messing around" via member function of the object. This makes it so that you do not have to keep track of specific addresses. vlad from moscow is spot about vectors reallocating memory.

2: Normally if you have a custom class written you would just make any functions apart of the class or a class that it was inherited from if redundant code is what you are trying to prevent. But otherwise in that case you access the variables via the dereferance operator ->.
Last edited on
Topic archived. No new replies allowed.