Вопрос

Question: How do you access a value at a specified position in a key range without loops?
The only possible way I know to acquire this data is by incrementing the iterator however many times the position is from the beginning or end of a key range.

edit The reason I am reluctant in using loops is to reduce processing time by getting the wanted value when the values position in an index is known.

Это было полезно?

Решение

As properly stated in the comments, you basically cannot do this on multimap. Or on map. Or on any container that does not support random access. The simple answer to the question "Why I cannot do this?" is "Because it is not in the interface".

The longer answer requires a minimal understanding of the implementation of different containers. Elements of, say, vector are stored in the memory consequently. Knowing address of the i-th element, you can add k and acquire the address of i+k-th element.

Maps (and multimaps) are different. To allow an efficient way of associative access they use some kind of trees as an underlying data structure. The simplest is the binary search tree. And all nodes of the tree are allocated in the heap. You don't know where before you actually access them. But you can access a node only through other nodes.

What you can do is to go through all elements and store their addresses in a vector, so they can now be accessed "randomly". However, this vector is invalidated once a new element is added or an element is removed from the map. There is no magic data structure which allows you both effective associative and random access.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top