检查std :: map的迭代器是否指向倒数第二个元素

Dan*_*nny 3 c++ dictionary iterator stdmap reverse-iterator

我(向前)遍历std :: map,并希望查找迭代器是否指向倒数第二个元素。我似乎找不到任何地方的方法。

我有:

bool
isSecondLastFile(const TDateFileInfoMap::const_iterator &tsFile)
{
    TDateFileInfoMap::reverse_iterator secondLastIt = mFileInfoMap.rbegin()  + 1;
    return (tsFile == secondLastIt);
}
Run Code Online (Sandbox Code Playgroud)

TDateFileInfoMapstd :: map 在哪里

我越来越:

error: no match for ‘operator==’ in ‘tsFile == secondLastIt’
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_tree.h:287: note: candidates are: bool std::_Rb_tree_const_iterator<_Tp>::operator==(const std::_Rb_tree_const_iterator<_Tp>&) const [with _Tp = std::pair<const long int, TFileInfo>]
Run Code Online (Sandbox Code Playgroud)

这是否意味着我无法比较正向和反向迭代器?

我如何确定正向迭代器是否指向倒数第二个元素?

jag*_*ire 5

std::map迭代器类型为BidirectionalIterator。只需将end迭代器递减两次-首先获取最后一个元素,因为m.end()在结束位置之后的位置返回了迭代器,然后再次获取了倒数第二个元素:

auto penultimate = std::prev(m.end(), 2);
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地使用结果迭代器检查是否相等:

auto it = m.begin();
it == penultimate;
Run Code Online (Sandbox Code Playgroud)

在Coliru上实时观看

自然,如果程序中的其他逻辑不能保证映射不包含两个元素,则应首先检查该映射。

  • 连续的“ operator--”几乎不可读。为什么不使用`auto back = std :: prev(m.end(),2)`? (2认同)