I have a list like below
typedef std::list<std::string> SegmentValue;
then in a iteration I need check if this is last iteration.
for(Field::SegmentValue::const_iterator it = m_segmentValue.begin();It !=
m_segmentValue.end();It++){
if((segIt + 1) == m_segmentValue.end())//last iteration
...
}
but I get error in compile that:
error C2678: binary '+' : no operator found which takes a left-hand operand of type 'std::list<_Ty>::_Const_iterator<_Secure_validation>'
how I can check if this is last itration?
You can’t use binary
+and-operators withstd::listiterators.std::listiterators are bidirectional iterators, but they are not random access iterators, meaning that you can’t shift them by an arbitrary constant value.Use unary
++and--insteadNow
it_lastis the last element iterator. Just make sure it remains valid. If you are not making any iterator-invalidating modifications to your container, you can pre-computeit_lastand use it in the cycle. Otherwise, you’ll have to re-compute it as necessary.In fact, in generic algorithms it is always a good idea to prefer using
--and++with iterators whenever possible (instead of binary+ 1and- 1), since it reduces your algorithm’s requirements: binary+and-require random access iterators, while++and--work with bidirectional ones.