TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C++ Coding Standard

Rule:  CFL#018Checked automatically with code checker

Synopsis:In for-conditions, compare iterators using != instead of < or >
Severity Level:4
Category:Control Flow


Especially when iterating over a container such as a list, the address of the next element is not necessarily greater than that of the previous element. Random-access iterators define "<" and ">" operators, but bi-directional iterators do not. When iterating over the container from begin to end, one should therefore compare the current iterator value using the != operator with the one-past-the-end value. This is portable across all iterator types.


#include <iostream>
#include <vector>
#include <list>

<   typename IteratorType
MRCPP_PrintCollection(	// algorithm does not depend on container type!
    IteratorType it_begin,
    IteratorType it_end,
    std::ostream& os)
    for (IteratorType it = it_begin; it != it_end; ++it)
        os << *it << std::endl;

    const size_t	n = 3;

    // print an n-element built-in array using pointer-type iterators:
    int			iarray[n] = {1, 2, 3};
    MRCPP_PrintCollection(iarray, iarray + n, std::cout);

    // print a std::vector using random-access iterators:
    std::vector	ivector(iarray, iarray + n);
    MRCPP_PrintCollection(ivector.begin(), ivector.end(), std::cerr);

    // print a std::list using bi-directional iterators: (no < operator)
    std::list<int>	ilist(iarray, iarray + n);
    MRCPP_PrintCollection(ilist.begin(), ilist.end(), std::clog);