Reputation: 941
I want to count the occurrences of same Points in a vector of pairs.
Here is my code:
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]));
}
The result should be:
[1, 2] [1, 1] - 3 Occurrences
[2, 2] [1, 1] - 2 Occurrences
[3, 2] [1, 2] - 1 Occurrence
[3, 2] [1, 1] - 1 Occurrence
I know you can use a map with a key (like a histogram) that tracks the occurrences and I tried something like:
map<pair<Point2f, Point2f>, int> pairToCount;
But I am not an expert at C++ lambda and don't know how to use this pairToCount
Upvotes: 0
Views: 1592
Reputation: 217980
Assuming:
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);
}
You can simply do:
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";
}
Upvotes: 1