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).
This type of sorting can be achieved using simple “ sort() ” function. By default the sort function sorts the vector elements on basis of first element of pairs. Case 2 : Sorting the vector elements on the basis of second element of pairs in ascending order.
Sorting a Vector in C++ in Ascending order A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.
Create vector indexes; fill it by values 0..n-1 than
struct CmpMass {
{
CmpMass(vector<double>& vec) : values(vec){}
bool operator() (const int& a, const int& b) const
{
return values[a] < values[b];
}
vector<double>& values;
}
sort(indexes.begin(), indexes.end(), CmpMass(mass));
than you have in vector indexes order of items in both arrays. Than you can create mass/velocity vectors in correct order or convert index during access: mass[indexes[i]], velocity[indexes[i]]
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