将两个 std::vector<cv::P oint> 向量和安全公共点与第三个 std::vector<cv::P oint 进行比较>

Compare two std::vector<cv::Point> vectors and safe common points to a third std::vector<cv::Point>

本文关键字:lt cv gt vector oint std 比较 三个 安全 两个 向量      更新时间:2023-10-16

我正在寻找std::set_intersection函数的替代版本,但std::vector<cv::Point>向量除外。

我尝试比较两个不同大小的std::vector<cv::Point>矢量。这两个包含坐标列表。类似交集的方法现在的主要任务应该是检测公共对,并通过push_back() 将它们安全地发送给第三个std::vector<cv::Point>

我搜索了一个类似std::set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v3)); 的函数

有什么办法解决这个问题吗?

正如@BoBTFish和@NaCl已经提到的,您需要使用自定义比较器,并在排序的向量上应用set_intersection

由于您需要调用比较器三次,因此使用函数而不是lambda表达式非常有用。

#include <opencv2/opencv.hpp>
#include <vector>
#include <algorithm>
using namespace std;
using namespace cv;
// Custom less comparator
bool lessPoints(const Point& lhs, const Point& rhs) {
    return (lhs.x < rhs.x) || ((lhs.x == rhs.x) && (lhs.y < rhs.y));
}
vector<Point> intersection(vector<Point> v1, vector<Point> v2)
{
    vector<Point> v3;
    // Sort vectors
    sort(v1.begin(), v1.end(), lessPoints);
    sort(v2.begin(), v2.end(), lessPoints);
    // Intersect
    set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(v3), lessPoints);
    return v3;
}
int main()
{
    // Your vectors
    vector<Point> v1{ Point(2,3), Point(1,2), Point(5,5), Point(3,4) };
    vector<Point> v2{ Point(2,1), Point(1,2), Point(3,4), Point(6,7), Point(0,3) };
    // Find intersections
    vector<Point> v3 = intersection(v1, v2);
    // Print out vector content
    std::copy(v3.begin(), v3.end(), std::ostream_iterator<Point>(std::cout, " "));
    return 0;
}