Here is my code:
#include <iostream> #include <map> using namespace std; int main() { map<int , int > myMap; map<int , int>::iterator it; myMap.insert(pair<int , int>(1,2)); myMap.insert(pair<int , int>(671,223)); myMap.insert(pair<int , int>(353,245352)); it = myMap.end() - 1; cout << it->first << it->second << endl; return 0; }
Compiling this code produces the following compilation error:
error: no match for ‘operator-’ (operand types are ‘std::map<int, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const int, int> >}’ and ‘int’) it = myMap.end() - 1;
I don't know why I am getting this error as I think arithmetic operations are allowed in all types of iterators.
It appears that you can still decrement the iterator returned from end() and dereference the decremented iterator, as long as it's not a temporary.
C++ Map Library - end() Function The C++ function std::map::end() returns an iterator which points to past-the-end element in the map. The past-the-end element is the theoretical element that would follow the last element in the map.
insert() doesn't overwrite.
Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.
Not all iterator categories support arithmetic operations, that's a misconception. If you aim to write more generic code, you can use std::prev
:
it = std::prev(myMap.end());
It expects a bidirectional iterator, which std::map
's iterator is. If you want to move the iterator more than a single step, it can also accept a second parameter that designated how far to move the iterator.
In addition, when you pass it a random access iterator, it will be as fast as the arithmetic.
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