1

したがって、基本的には、他のメンバーとともに、3D ポイントを表すxy、およびzの値を持つ構造体があります。次に、いくつかの関数によって構築された上記の構造体のベクトルがあります。

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

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

ここで、3D ポイント (x、y、z メンバー) と空間内の別の変数ポイントとの間の距離によって、ベクター内の構造体を並べ替えたいと思います。構造体のメンバーを 1 つずつ再構築しなくても可能です (それらはまたは、最初のベクトル構築関数を完全に作り直しますか?

4

2 に答える 2

2

std::sort次のように、ラムダで使用できます。

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;
});
于 2013-07-13T23:35:41.723 に答える
1

はい、コンパレータ関数またはファンクターを使用して可能です。

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); 
   }
}

そして後で std::sort を呼び出します:

vector<myStruct> myVector = myVectorBuildingFunction(...);
myStruct point = {1,2,3}; // define that 'another varialbe`
std::sort(myVector.begin(), myVector.end(), byDistTo(point));
于 2013-07-13T23:37:15.683 に答える