is there an iterator across unique keys in a std::multimap?

前端 未结 6 1960
无人及你
无人及你 2020-11-29 08:18

Is there a simple or standard way to have a multimap iterator which iterate across unique keys in a multimap?

i.e. for a set that looks like: {1, \"a\"}, {1, \

6条回答
  •  天涯浪人
    2020-11-29 08:30

    You can use upper_bound to increment the iterator position instead of ++:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
      multimap mm;
      mm.insert(make_pair(1, "a"));
      mm.insert(make_pair(1, "lemon"));
      mm.insert(make_pair(2, "peacock"));
      mm.insert(make_pair(3, "angel"));
    
      for( auto it = mm.begin(), end = mm.end();
           it != end;
           it = mm.upper_bound(it->first)
      )
        cout << it->first << ' ' << it->second << endl;
      return 0;
    }
    

    This results in:

    1 a
    2 peacock
    3 angel
    

提交回复
热议问题