& ldquo; locking & rdquo; two vectors and sort them

advertisements

I have this two vector<double> 's mass and velocity both of the same size N. They contain the information about the mass and velocity of N particles. mass[i] and velocity[i] are thus properties of the i'th particle

Is it possible in C++ to "lock" these two vectors together and sort them in increasing order of mass? Thus after the sorting the vector mass should be in increasing order, and the velocity vector should contain the corresponding velocities of the sorted masses

e.g. Before sorting mass = (4,2,1,3) and velocity = (13, 14,15,16 ) After sorting mass=(1,2,3,4) and velocity =(15, 14, 16, 13)

The one (non-efficient) way I know for this is to transfer the data into an vector of struct's

struct particle
{

double mass;
double velocity;

bool operator < (const particle& str) const

 {
    return (mass < str.mass);
  }

};

and create vector<particle> particlelist(N) and then sort this vector by using the std::sort by overloading the < operator as I have done in the definition above.

I do not want to put my data into Array of Structures fashion since I have heard it is inefficient compared to the Structure of Arrays approach(at least in CUDA).


At least as far as I know, none of the sorting algorithms built into the standard library will do this for you directly. The most obvious possibility would probably be to use a Boost Zip Iterator to make the two arrays act like a single collection.