Search code examples
c++stdmultimap

Count occurrences by object id in std::multimap


I'm trying to find the occurrences of an object in a std::multimap

Here is my object Point:

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 );
    }

};

Here is my function (solution):

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;
}

My main:

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;

Initially, I wanted to count the number of occurrences with the operator==, but it was counting with the operator<. Using the function countOccurrences() is my solution.


Solution

  • But it doesn't works, il only returns 1 and there are at least 2 objects in my map that have same id

    It's a std::map. You cannot have two objects with the same key, and I assume you're trying to use the m_id filed of O as your key. Try using std::multimap instead.

    And, to count the number of items, use map::count() (which for std::map can only return one or zero!)