Reference to object in 2d vector


I have a class named Spring in a particle system. The constructor looks like:

Spring(Particle& _a, Particle& _b);  

And I have a vector of Particles and I use

Spring mySpring = Spring(,;  

inside a loop to add a spring force between two particles. Everything works fine so far. However, I want to use a 2d vector of Particles. That is:

Spring mySpring = Spring(,;  

And I don’t get a reference to the particle. In the first example, whenever I change the particle in my spring class, the particle in the vector gets changed. In the second example the changes are only locally. How can I change the particles in the 2D Vector?

This looks right to me. The problem may be somewhere else. If I’m understanding correctly, you are trying to change the values of the particles in the Spring constructor, but after you call it you observe the old values for the particles?

Would you be able to share some more code, such as:

  • The myParticles declaration and initialization

  • the actual Spring constructor code

  • How you’re checking the particle values after calling the Spring constructor

I ask because at first glance this code looks like the proper way to do what you want.

I agree with jacksonM, this looks right, but it would help to know what does the particle vector look like?

vector <vector > particles;


vector <vector <particle*>> particles;

and did you try:

myParticles[i][j] ?

I guess that’s probably the same as at(i).at(j) but I find it easier to read.

I’ve seen problems with using the memory adress of a space in a vector, since the memory gets moved around. I always recommend people to use a vector of pointers for what you are trying to do, which is store memory addresses to objects in a vector.

take care,

zach’s right - your vector needs to be a vector of Particle* (pointers to Particles), and your Spring should take Particle*'s…

so your vector is

vector<Particle*> myParticles;  

and your spring class has:

class Spring {  
  Spring( Particle* _a, Particle* _b );  
  Particle *a, *b;  

the reason for this is that when you use the & to specifiy a reference, and then you use an = somewhere for assignment, you’re invoking the copy constructor rather than passing the reference on:

Particle a;  
Particle& b = a; // b references a so if you change b now you will also change a  
Particle c = b; // c is a copy of a, so if you change c a will not change.  

basically, the vector type is opaque in the way it manages memeroy: when you want to use something inside a vector from somewhere else, you need the vector to be storing pointers, and then pass around these pointers. the reason for this is that if you add things to a vector later it can and will reallocate memory and copy itself to somewhere else, so that all of your old references to inside the vector are no longer valid…

hth… against common wisdom i believe that pointers aren’t difficult, they’re just a bit weird more than anything else.