【问题标题】:Ordering Points based on their distance to each other ?根据彼此之间的距离订购点 ?
【发布时间】:2013-08-19 17:03:15
【问题描述】:

我有一个包含 3 个点 A、B 和 C 的向量我想根据这些点之间的距离来排序这个向量,比如最大的距离是 B 和 C 之间的距离,而不是 C 和 A 之间的距离,最后是 A 和 B 之间的距离:

我该怎么做???

std::sort(vectorName.begin(), vectorName.end(), 
          [](const cv::Point2f &a, const cv::Point2f &b)
          {
              cv::Point2f diff = a-b;
             return  cv::sqrt(diff.x*diff.x + diff.y*diff.y); // I know it doesn't make a sense but how can I do this 
          });

【问题讨论】:

  • 简而言之,你不能,因为这没有定义一个strict weak order,这是所有标准库排序机制所必需的。举个简单的例子,等边三角形的点应该按什么顺序排列?您需要更仔细地考虑您希望积分结束的顺序。
  • 您只能根据到固定点(比如原点)的距离对点进行排序,而不是相对于彼此的距离。
  • @TemplateRex 根据与(0,0) 的距离对(0,1)(1,0) 进行排序。
  • 曼哈顿距离足够好,而且快得多。
  • @DieterLücking “足够好”,因为它以同样的方式失败?

标签: c++ opencv


【解决方案1】:

如果问题被改写:获取排序向量中点之间的所有曼哈顿距离:

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

struct Point { int x; int y; };
struct ManhattanDistance {
    std::size_t a;
    std::size_t b;

    int value;

    ManhattanDistance(std::size_t index_a, const Point& a, std::size_t index_b, const Point& b)
    :   a(index_a), b(index_b), value(abs(b.x - a.x) + abs(b.y - a.y))
    {}

    operator int () const { return value; }
};

inline std::ostream& operator << (std::ostream& stream, const ManhattanDistance& x) {
    return stream << x.a << " - " << x.b << ": " << x.value;
}

int main()
{
    typedef std::pair<std::size_t, std::size_t> Pair;
    std::vector<Point> points = { {0,0}, {2,2}, {3,3}, {4,4}, {5,5} };
    std::vector<ManhattanDistance> distances;
    distances.reserve(points.size() * (points.size() - 1) / 2);
    for(std::size_t a = 0; a < points.size() - 1; ++a) {
        for(std::size_t b = a + 1; b < points.size(); ++b) {
            distances.push_back(ManhattanDistance(a, points[a], b, points[b]));
            std::cout << "Add: " << distances.back() << std::endl;
        }
    }
    std::sort(distances.begin(), distances.end(), std::greater<ManhattanDistance>());
    for(const auto& d: distances) std::cout << "Sorted: "  << d << '\n';
    std::cout << std::endl;
    return 0;
}

【讨论】:

    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多