Banderi
Banderi

Reputation: 710

Sorting an array of structs by particular members of said structs?

So basically, I have a struct that, along with other members, has x, y and z values to represent a 3D point; I have then a vector of said structs which is built by some functions.

struct myStruct{
    char x;
    char y;
    char z;
    // some other members
};

vector<myStruct> myVector = myVectorBuildingFunction(...);

Now, I would like to sort the structs in the vector by the distance between their 3D point (x, y, z members) and another variable point in the space.. is that possible without rebuilding the structs' members one by one (they're relatively many) or remaking entirely my initial vector building function?

Upvotes: 1

Views: 97

Answers (2)

sasha.sochka
sasha.sochka

Reputation: 14715

Yes, it's possible using comparator function or functors.

struct byDistTo {
   myStruct point;
   byDistTo(myStruct point): point(point){}
   bool operator() (const& myStruct a, const& myStruct b) const {
     // define getDistance yourself
     return getDistance(a, point) < getDistance(b, point); 
   }
}

And later call std::sort:

vector<myStruct> myVector = myVectorBuildingFunction(...);
myStruct point = {1,2,3}; // define that 'another varialbe`
std::sort(myVector.begin(), myVector.end(), byDistTo(point));

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You can use std::sort with lambdas, like this:

myStruct pointOfInterest = ...; // Set the point of interest
sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [&](const myStruct & lhs, const myStruct & rhs) -> bool
{
    double distanceLhs = computeDistance(pointOfInterest, lhs);
    double distanceRhs = computeDistance(pointOfInterest, rhs);
    return distanceLhs < distanceRhs;
});

Upvotes: 2

Related Questions