Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a std::map, which I want to iterate over, starting at the second entry.

I can workaround this fine, but I'm confused about why the "obvious" syntax doesn't compile. The error message doesn't help, because it refers to std::string, which I'm not using here.

Here's 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 gives the following error on 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 happening here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

std::map<T>::iterator is of the iterator-class bidirectional iterator. Those only have ++ and -- operators. +N and [] is only available for random access iterators (which can be found in e.g. std::vector<T>).

The reason behind this is that adding N to a random access iterator is constant time (e.g. add N*sizeof(T) to a T*), whereas doing the same thing for a bidirectional iterator would require applying ++ N times.

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

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

which does the right thing for all iterator types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...