简体   繁体   English

为什么我不能在 c++ 的 `map` 的迭代器中使用 `+1`?

[英]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::iteratorLegacyRandomAccessIterator It is required to support the operation it + 1 .它需要支持操作it + 1

On the other hand, std::map::iterator is a LegacyBidirectionalIterator .另一方面, std::map::iteratorLegacyBidirectionalIterator 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 add N*sizeof(T) to a T* ), 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+ . itstd::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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM