[英]Why I can't use `+1` in the iterator of `map` in c++?
I have a problem about the iterator using in map
.我对在
map
中使用的迭代器有疑问。 I have a map with type of map<int, vector<int> > vpmap;
我有一个 map 类型为
map<int, vector<int> > vpmap;
I want to loop through the whole map.我想遍历整个 map。 Then I use
然后我用
for (size_t i = 0; i < vpmap.size(); i++) {
{
auto it = vpmap.begin();
it++;
/*code*/
}
This is well.这很好。 But when I replace the
it++
to it=it+1
.但是当我将
it++
替换为it=it+1
。 The complier gives an error.编译器给出错误。 I haven't get this error before when using
vector
.在使用
vector
之前,我没有收到此错误。 I would like to know the reason of it.我想知道它的原因。
std::vector::iterator
is a LegacyRandomAccessIterator . std::vector::iterator
是LegacyRandomAccessIterator 。 It is required to support the operation it + 1
.它需要支持操作
it + 1
。
On the other hand, std::map::iterator
is a LegacyBidirectionalIterator .另一方面,
std::map::iterator
是LegacyBidirectionalIterator 。 It is not required to support it + 1
but it is required to support it++
as well as it--
.不需要支持
it + 1
,但需要支持it++
和it--
。
Relevant detail from an answer to a different post :来自不同帖子答案的相关细节:
The reason behind this is that adding
N
to a random access iterator is constant time (eg addN*sizeof(T)
to aT*
), whereas doing the same thing for a bidirectional iterator would require applying++
N
times.这背后的原因是,将
N
添加到随机访问迭代器是恒定时间(例如,将N*sizeof(T)
添加到T*
),而对双向迭代器执行相同操作则需要应用++
N
次。
it
is the iterator of std::map
, it's an Bidirectional Iterator and doesn't support operator+
. it
是std::map
的迭代器,它是双向迭代器,不支持operator+
。
RandomAccess Iterator supports operator+
, eg the iterator of std::vector
, that's why you did not get this error with std::vector
. RandomAccess Iterator支持
operator+
,例如std::vector
的迭代器,这就是为什么你没有使用std::vector
得到这个错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.