0

Similar to this thread, I'm trying to get the integer index from an iterator but for a map instead of an vector. Atm its causing a large bottle neck in my code and I was wondering if there was a more efficient way to get the index other that what I'm doing currently...

auto itTail = nodesMap.find(tail);
tailNodePos = distance(nodesMap.begin(), itTail);
4
  • map iterators are invalidated at insertions AFAIK, are the element stable or you're planning on inserting/deleting a lot?
    – Marco A.
    Commented Jun 22, 2014 at 17:07
  • What is the point of tailNodePos? You cannot really use it to insert elements. Just save tail and use it to find the position again or save the iterator itTail. Keep in mind the invalidation on every insert / erase.
    – nwp
    Commented Jun 22, 2014 at 17:23
  • The elements are stable... I'm using the map to build an adjacency list represented by a vector of vectors, where the position in the first vector corresponds to the position of a corresponding element in the map Commented Jun 22, 2014 at 17:28
  • 4
    If the map is stable, what is the point of using the map? Sorting + binary search is a better option if no inserts/deletes are performed.
    – kraskevich
    Commented Jun 22, 2014 at 17:31

2 Answers 2

0

I would say it is impossible to get the index for an arbitrary iterator for a map faster than O(container size)(according to map specification in C++ standard). If it is very important to do it much faster, I would try using custom balanced binary search tree(because it is possible to get an index for a node in a tree in O(log(container size)) if each node in a tree maintains sub tree size).
And if there are no inserts and deletes performed, it is easy to use sorted vector and lower_bound instead of map and find(this approach allows to get the index in O(1) because vector iterator is a random access iterator).

0

If you want a container with fast indexing (nth element, and index-of-element) and fast sort-ordered insert/delete, you will have to write your own, or find one outside of std.

It is not that tricky a design -- a b-tree or rb-tree where each node also keeps count of how many nodes are under it has only a modest overhead over a 'naked' one. Writing the rest of the interface to match std::map is a slog, as is writing raw tree manipulation code.

I tried to find one in boost a few years ago and failed. Maybe something with multi-index container: but there, the sequence is order of insertion, not order-in-map component.

Not the answer you're looking for? Browse other questions tagged or ask your own question.