sorting elements in a vector of curves

70 views Asked by At

I have a class point which represents the x and y coordinate and class curve which have two point, start point and end point.

class point {
public:
    double x{0.0}, y{0.0};
    //.........
}

class curve {
public:
    point start, end;
    //.........
}

I have a vector of curves, which needs to be sorted. start point of one curve equals the end point of the other. The Output curve (keeping one curve after the other) can be an open curve or close curve(always a continuous curve).

Current logic with lot of loops and 2/3 vectors.. Is there a way to implement the same using standard algorithms(c++11).

1

There are 1 answers

1
leJon On BEST ANSWER

Assuming that the first element of the vector is the starting point of the path and that there is only one solution, the following lines will do the job:

bool operator!=(point& a,point& b) {
    return !(a.x == b.x && b.y == a.y);
}

bool operator==(point& a, point& b) {
    return (a.x == b.x && b.y == a.y);
}

void order(std::vector<curve>& vin) {
    auto it = vin.begin();
    auto end = vin.end();
    while (it+1 != end) {
        if (it->end != (it + 1)->start) {
            std::swap(*(it + 1), *std::find_if(it + 2, end, [it](curve& c){ return c.start == it->end ;  }));
        }
        ++it ;
    }
}

if you need to find the first element, just define a predicate is_the_beginning and do a similar call to swap before the loop:

bool is_the_beginning(curve& c) {
    if ( ... )  return true;
    else return false ;
}
std::swap(*it, *std::find_if(it+1, end, is_the_beginning ) ) ;

Maybe you will need to take into account the precision of the double for the operator == and !=. You can also replace them by functions