Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if iterator to std::map points to second last element

I'm (forward) iterating over a std::map and would like to find if the iterator points to the second last element. I can't seem to find how to do that anywhere.

I've got:

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

Where TDateFileInfoMap is std::map

I'm getting:

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>]

Does that mean I can't compare the forward and reverse iterator?

How do I figure out if the forward iterator is pointing at the second last element?

like image 423
Danny Avatar asked Feb 06 '23 16:02

Danny


1 Answers

std::map's iterator type is BidirectionalIterator. Just decrement the end iterator twice--first to get the last element since m.end() returns an iterator at the after the end position, and then again to get the second-last element:

auto penultimate = std::prev(m.end(), 2);

Then you can simply check for equality with the resultant iterator:

auto it = m.begin();
it == penultimate;

see it live on Coliru

Naturally, you should check that the map has two elements first if it's not guaranteed by other logic in your program.

like image 72
jaggedSpire Avatar answered Feb 24 '23 12:02

jaggedSpire