为什么我不能做std :: map.begin()+ 1?

时间:2013-07-05 08:25:48

标签: c++ visual-c++ visual-studio-2012 stl

我有一个std::map,我想从第二个条目开始迭代。

我可以解决这个问题,但我很困惑为什么“明显的”语法无法编译。错误消息没有帮助,因为它引用std::string,我在这里没有使用。

这是一些代码

// 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在上面的行中给出以下错误

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'

有谁能解释这里发生了什么?

2 个答案:

答案 0 :(得分:14)

std::map<T>::iterator是迭代器类双向迭代器。那些只有++--运算符。 +N[]仅适用于随机访问迭代器(可在std::vector<T>中找到)。

这背后的原因是将N添加到随机访问迭代器是恒定时间(例如将N*sizeof(T)添加到T*),而执行此操作对于双向迭代器,同样需要应用++ N次。

你可以做的(如果你有C ++ 11)是:

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

对所有迭代器类型都做正确的事。

答案 1 :(得分:6)

std::map迭代器是双向的,因此它们只提供++和 - 运算符,但不提供operator+,即使它是+1。 如果你真的需要模拟operator +,你可以使用std::advance,但这会导致为迭代器调用增量序列。