Why can't I do std :: map.begin () + 1?

I have a std::map that I want to iterate over starting from the second record.

I can get around this normally, but it bothers me why the "obvious" syntax does not compile. The error message does not help, because it refers to std::string , which I do not use here.

Here is some code

 // Suppose I have some map ... std::map<int, int> pSomeMap; // This is fine ... std::map<int, int>::const_iterator pIterOne = pSomeMap.begin(); ++pIterOne; // This doesn't compile ... std::map<int, int>::const_iterator pIterTwo = pSomeMap.begin() + 1; 

Visual Studio 2012 throws the following error in the above line:

 error C2784: 'std::_String_iterator<_Mystr> std::operator + (_String_iterator<_Mystr>::difference_type,std::_String_iterator<_Mystr>)' : could not deduce template argument for 'std::_String_iterator<_Mystr>' from 'int' 

What's going on here?

+8
source share
2 answers

std::map<T>::iterator refers to a bidirectional iterator of the iterator class. They have only ++ and -- operators. +N and [] are available only for random access iterators (which can be found, for example, std::vector<T> ).

The reason for this is that adding N to a random access iterator is a constant time (for example, add N*sizeof(T) to T* ), whereas for the same iterator, a bidirectional iterator needs to be applied ++ N times.

What you can do though (if you have C ++ 11):

 std::map<int, int>::const_iterator pIterTwo = std::next(pSomeMap.begin(),1); 

which does the right thing for all types of iterators.

+14
source

std::map iterators are bidirectional, so they provide only ++ and - operators, but not operator+ , even if it's +1.
You can use std::advance if you really need to simulate the + operator, but this will result in a sequence of increments for the iterator.

+6
source

Source: https://habr.com/ru/post/948768/


All Articles