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);
Community
  • 1
  • 1
Barnaby Hussey-Yeo
  • 647
  • 2
  • 8
  • 15
  • map iterators are invalidated at insertions AFAIK, are the element stable or you're planning on inserting/deleting a lot? – Marco A. Jun 22 '14 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 Jun 22 '14 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 – Barnaby Hussey-Yeo Jun 22 '14 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 Jun 22 '14 at 17:31

2 Answers2

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).

kraskevich
  • 18,368
  • 4
  • 33
  • 45
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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524