Search code examples
c++sortingmultimap

3 element multimap, sort by the first but count the second number


I'm using std::multimap in this way

std::multimap<float, std::pair<int, int> > edges;

I want to sort it by the first float number, but later count how many int (the first one of <int, int>) are in this multimap.

for example, I have element pairs (0.6001, <2,3>), (0.62, <2,4>), (0.63, <1,3>) in my multimap, I want to count the number of <2,*> (it should be 2 here).

Is there a simpler way (something like edges.count()) than to get every element out and count?

Or is there another container that I could turn to?

#

Solution 1 I'll first store the values I need to count in a std::set and count as codes given by jrok or johny;

Solution 2 I'll use a std::multimap to store the second and third element again and count.

Thank you both jrok and johny!


Solution

  • What about this?

    std::multimap<float, std::pair<int, int> > edges;
    typedef std::multimap<float, std::pair<int, int> >::value_type ElemT;
    
    int value = 2;
    int count = 
    std::count_if(edges.begin(), edges.end(),
        [value](const ElemT& e) { return e.second.first == value; });