我正在(向前)迭代 std::map 并想知道迭代器是否指向倒数第二个元素。我似乎无法在任何地方找到如何做到这一点。
我有:
bool
isSecondLastFile(const TDateFileInfoMap::const_iterator &tsFile)
{
TDateFileInfoMap::reverse_iterator secondLastIt = mFileInfoMap.rbegin() + 1;
return (tsFile == secondLastIt);
}
TDateFileInfoMap
是 std::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>]
这是否意味着我无法比较正向和反向迭代器?
如何确定前向迭代器是否指向倒数第二个元素?
最佳答案
std::map
's迭代器类型是 BidirectionalIterator
.只需将 end
迭代器递减两次——首先获取最后一个元素,因为 m.end()
在结束位置之后返回一个迭代器,然后再次获取最后一个元素倒数第二个元素:
auto penultimate = std::prev(m.end(), 2);
然后您可以简单地检查结果迭代器是否相等:
auto it = m.begin();
it == penultimate;
当然,如果您的程序中的其他逻辑不能保证,您应该首先检查映射有两个元素。
关于c++ - 检查 std::map 的迭代器是否指向倒数第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38079949/