【问题标题】:sorting elements in a vector of curves对曲线向量中的元素进行排序
【发布时间】:2015-06-19 14:13:51
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 这不是排序问题,而是排序问题。您需要知道如何找到要排序的订单。

标签: sorting c++11 stl-algorithm


【解决方案1】:

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

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 并在循环之前执行类似的 swap 调用:

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 的精度。你也可以用函数替换它们

【讨论】:

  • 确实你是对的,我会再看一遍并测试你的答案,因为我发现这是一个有趣的问题!
猜你喜欢
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
相关资源
最近更新 更多