我試圖找到一個對象出現在一個std :: multimap中計數出現的對象ID的std :: multimap中
這是我的目標點:
class Point
{
public:
Point(string id, float x, float y, float z);
string m_id;
float m_x;
float m_y;
float m_z;
//I want to count with this operator
bool operator==(const Point &point) const
{
return point.m_id == m_id;
}
bool operator <(const Point &point) const
{
return (m_y < point.m_y);
}
};
這裏我的函數(解決方案):
int countOccurences(multimap<Point, string> multimap, Point point)
{
int result = 0;
for (auto it = multimap.begin(); it != multimap.end(); it++)
if (it->first == point)
result++;
return result;
}
我的主:
multimap<Point, string> places;
Point point1("point", 0, 0, 0);
Point point2("cake", 0, 0, 0);
Point point3("point", 0, 0, 0);
places.insert(make_pair(point1, ""));
places.insert(make_pair(point2, ""));
places.insert(make_pair(point3, ""));
cout << "CORRECT = 2" << endl;
cout << "COUNT = " << places.count(point3) << endl;
cout << "MY_COUNT = " << countOccurences(places, point3) << endl;
最初,我想用運算符==來計算出現次數,但它是與運算符<一起計算的。使用函數countOccurrences()是我的解決方案。
[您需要創建一個最小,完整和可驗證的示例。](http://stackoverflow.com/help/mcve) – Xirema
首先,我們不知道'S'是什麼。 –
地圖中的按鍵必須是唯一的。關鍵要麼存在要麼只有一個。如果你想看看是否存在一個鍵,然後使用['std :: map :: find()'](http://en.cppreference.com/w/cpp/container/map/find) – NathanOliver