我想计算成对矢量中相同点的出现次数。
这是我的代码:
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;
但我不是C ++ lambda的专家,也不知道如何使用这对TOCount
答案 0 :(得分:1)
假设:
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";
}