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

前端 未结 6 1949
无人及你
无人及你 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:26

    Using upper_bound would result in an easy-to-read loop but each call will perform a binary tree search, resulting in an O(n log n) instead of O(n) traversal. If the difference in efficiency matters, you can structure your traversal like this:

    typedef std::multimap MapType;
    MapType container;
    for (MapType::iterator it = container.begin(); it != container.end(); ) {
      std::string key = it->first;
    
      doSomething(key);
    
      // Advance to next non-duplicate entry.
      do {
        ++it;
      } while (it != container.end() && key == it->first);
    }
    

提交回复
热议问题