代码之家  ›  专栏  ›  技术社区  ›  Grillteller

计算成对向量中的出现次数

  •  0
  • Grillteller  · 技术社区  · 7 年前

    我想计算成对向量中相同点的出现次数。

    这是我的代码:

    vector<Point2f> points_1, points_2;
    
    points_1.push_back(Point2f(1.0, 2.0));
    points_1.push_back(Point2f(2.0, 2.0));
    points_1.push_back(Point2f(3.0, 2.0));
    points_1.push_back(Point2f(1.0, 2.0));
    points_1.push_back(Point2f(2.0, 2.0));
    points_1.push_back(Point2f(3.0, 2.0));
    points_1.push_back(Point2f(1.0, 2.0));
    
    points_2.push_back(Point2f(1.0, 1.0));
    points_2.push_back(Point2f(1.0, 1.0));
    points_2.push_back(Point2f(1.0, 2.0));
    points_2.push_back(Point2f(1.0, 1.0));
    points_2.push_back(Point2f(1.0, 1.0));
    points_2.push_back(Point2f(1.0, 1.0));
    points_2.push_back(Point2f(1.0, 1.0));
    
    vector<pair<Point2f, Point2f>> point_pairs;
    for (size_t i = 0; i < points_1.size(); i++) {
        cout << points_1[i] << " " << points_2[i] << endl;
        point_pairs.push_back(make_pair(points_1[i], points_2[i]));
    }
    

    结果应该是:

    [1, 2] [1, 1] - 3 Occurrences
    [2, 2] [1, 1] - 2 Occurrences
    [3, 2] [1, 2] - 1 Occurrence
    [3, 2] [1, 1] - 1 Occurrence
    

    我知道你可以使用带有关键点(如直方图)的地图来跟踪事件,我尝试了以下方法:

    map<pair<Point2f, Point2f>, int> pairToCount;
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jarod42    7 年前

    假设:

    std::ostream& operator << (std::ostream& os, const Point2f& pt)
    {
        return os << "[" << pt.x << ", " << pt.y << "]";
    }
    
    bool operator < (const Point2f& lhs, const Point2f& rhs)
    {
        return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
    }
    

    您可以简单地执行以下操作:

    const std::vector<std::pair<Point2f, Point2f>> point_pairs /* = */;
    map<pair<Point2f, Point2f>, int> counts;
    
    for (const auto& p : point_pairs) {
        ++counts[p];
    }
    
    for (const auto& p : counts) {
        const auto& p1 = p.first.first;
        const auto& p2 = p.first.second;
        int count = p.second;
        std::cout << p1 << " " << p2 << " - " << count << " Occurrence(s)\n";
    }
    

    Demo