Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting map iterators

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?

like image 463
user3811219 Avatar asked Jan 05 '23 02:01

user3811219


1 Answers

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.

like image 186
NathanOliver Avatar answered Jan 06 '23 14:01

NathanOliver