Sortowanie punktów 3d [struktura]

0

Dzień dobry,

Napisałem prosty program oparty o strukturę, który sortuje punkty 3d. Ale nie chciał działać więc znalazłem podobny w internecie i dodałem z niego kawałek kodu. Teraz wszystko działa ale nie rozumiem jak. Czy ktos mógłby mi wytłumaczyć co ten kod "robi"?

Kawałek kodu:

bool operator<(const P &o) const {
        if (x != o.x) {
            return x < o.x;
        }
        if (y != o.y) {
            return y < o.y;
        }
        return z < o.z;
    } 

Cały program:

 #include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct P {
    int x;
    int y;
    int z;

    P(int a, int b, int c) {
        x=a;
        y=b;
        z=c;
    }

    bool operator<(const P &o) const {
        if (x != o.x) {
            return x < o.x;
        }
        if (y != o.y) {
            return y < o.y;
        }
        return z < o.z;
    }
};

main()
{
    vector<P> p;
    int ile;
    cin>>ile;
    p.reserve(ile);

    for(int i=0; i<ile; i++) {
        int x,y,z;
        cin>>x>>y>>z;
        p.push_back(P(x,y,z));
    }

    sort(p.begin(), p.end());

    for(int i=0; i<ile; i++) {
        cout<<p[i].x<<" "<<p[i].y<<" "<<p[i].z<<endl;
    }
}
1

Przeciążasz operator dla struktury P, zwraca normalne boolowskie wartości, co zresztą widać w kodzie.
Funkcja sort z niego korzysta i elegancko Ci te punkty sotruje

http://www.cplusplus.com/reference/algorithm/sort/ ("The elements are compared using operator< for the first version")
http://pl.wikibooks.org/wiki/C++/Przeci%C4%85%C5%BCanie_operator%C3%B3w

1 użytkowników online, w tym zalogowanych: 0, gości: 1