Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement of end of std::map

Tags:

c++

stl

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.

like image 620
Bhawan Avatar asked Oct 09 '17 06:10

Bhawan


People also ask

Can I decrement end iterator C++?

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.

What does map end () do in C++?

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.

Does insert overwrite map C++?

insert() doesn't overwrite.

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.


1 Answers

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.

like image 186
StoryTeller - Unslander Monica Avatar answered Sep 30 '22 20:09

StoryTeller - Unslander Monica