c++ - 根据点之间的距离排序?

标签 c++ opencv

我有一个由 3 个点 A、B 和 C 组成的 vector ,我想根据这些点之间的距离对该 vector 进行排序,假设最大距离是 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 
          });

最佳答案

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

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

关于c++ - 根据点之间的距离排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308695/

相关文章:

C++模板矩阵类——方阵特化

c++ - 使用 C++ 中的 SetWinMetaFileBits api 将 wmf 文件转换为 emf 文件

c++ - 是否可以使用 ifstream 在 linux 中读取 dos 文件

c++ - 更快地读取带有 float 的文本文件并存储在浮点 vector 中

python - window : Python + OpenCV + Qt: "import cv2" gives "dll not found" error

c++ - C++ 类中的类

python - python-Opencv 或 numpy 中的非 sobel 离散梯度

python-3.x - 如何在opencv python中为摄像头视频赋予透明边框?

python - 建议在沙盘上检测直线,python

python - 定义线之间的距离