I have a program where I have two std::map
iterators say left
and right
respectively. I want to find the number of elements in the range [left,right].
I naively did something like this : int len = right - left
. I thought it would be just fine but it gave me an error
Then I discovered distance(left, right)
method thank to a post on Stack Overflow but unfortunately it has a linear time complexity.
Is it possible to get an O(1)
solution for this?
Is it possible to get an O(1) solution for this?
No. a std::map
has a BidirectionalIterator. A BidirectionalIterator does not support random access and can only be incremented or decremented. That means if you want to move 5 positions forward you have to call ++iterator_name
5 times. If you need random access then you will need to pick a container that supports that like a std::array
or std::vector
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With