对曲线向量中的元素进行排序

sorting elements in a vector of curves

我有一个 class 点代表 x 和 y 坐标, class 有两个点的曲线,起点和终点。

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

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

我有一个曲线向量,需要对其进行排序。 一条曲线的起点等于另一条曲线的终点。 输出曲线(保持一条曲线接一条曲线)可以是开放曲线或闭合曲线(始终是连续曲线)。

当前逻辑有很多循环和 2/3 向量.. 有没有办法使用标准算法 (c++11) 来实现相同的功能。

假设向量的第一个元素是路径的起点并且只有一个解决方案,则以下几行将完成这项工作:

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

如果您需要找到第一个元素,只需定义一个谓词 is_the_beginning 并在循环之前执行类似的交换调用:

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

也许您需要考虑运算符 ==!=double 的精度。你也可以用函数替换它们