std::distance
seems to be very slow. I have a large multimap and try to use equal_range
to find the element with common key:
auto range = in_map.equal_range(neuron_with_spikes[i]);
int count = std::distance(range.first, range.second);
The std::distance
takes more time than equal_range
.
Naively I would assume when doing equal_range, the distance is automatically calculated. In fact, it's two independent calculations.
Is there a different way to get the total number of element of the equal_range
?
No; it is possible to implement a std map type construct where counting the distance between iterators is O(lg n), but std maps do not implement it. And retrofitting it is not easy; writing your own container is probably just as easy.
In such a modified map, the balanced binary tree keeps track of total nodes under; this adds a constant overhead factor to tree mutation and memory usage, but none in O notation.
The easiest way, because you only need count and not distance, probably to replace your multimap with a map from key to vector of elements; and manually manage the vector of elements. Distance is O(n) but count becomes O(lg n).