为什么我不能做std :: map.begin()+ 1? [英] Why can't I do std::map.begin() + 1?
问题描述
我有一个 std :: map
,我想从第二个条目开始迭代。
I have a std::map
, which I want to iterate over starting at the second entry.
我可以解决这个罚款,但我很困惑为什么明显的语法不编译。错误消息没有帮助,因为它指的是 std :: string
,这里不使用。
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.
这里有一些代码
// 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;
VS2012在上述行中出现以下错误
VS2012 gives the following error on the above line
错误C2784:'std :: _ String_iterator< _Mystr> std :: operator +(_ String_iterator <_Mystr> :: difference_type,std :: _ String_iterator< _Mystr>):无法推导出模板参数for'std :: _ String_iterator< _Mystr>'from'int'
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'
任何人都可以解释这里发生了什么?
Can anyone explain what's happening here?
推荐答案
std :: map< T> :: iterator
> bidirectional iterator 。那些只有 ++
和 -
运算符。 + N
和 []
仅适用于随机存取迭代器 in std :: vector< T>
)。
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>
).
c> N 到 是恒定时间(例如添加 N * sizeof(T)
code> T * ),而对于双向迭代器做同样的事情将需要应用 ++
N
次。
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.
你可以做什么(如果你有C ++ 11) >
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.
这篇关于为什么我不能做std :: map.begin()+ 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!