gpt4 book ai didi

c++ - 根据彼此的距离排序点?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:49:17 24 4
gpt4 key购买 nike

我有一个包含 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com