Get length of the longest sequence of numbers with the same sign I need to get length of the longest sequence of numbers with the same sign. Assumes that zero is positive. For example:

{10, 1, 4, 0, -7, 2, -8, 4, -2, 0} → 4
{0, 1, 2, 3, -2, -4, 0}  → 4
{1, -2, 0, -1} → 1


I wrote a function:

unsigned getLongestSameSignSequenceLength(std::vector&lt;int&gt; const&amp; a)
{
    unsigned maxlen = 1;

/* Assumes that zero is positive. */
#define SIGN(a) (a &gt;= 0)

    for (size_t i = 1, len = 1; i &lt; a.size(); i++, len++) {
        if (SIGN(a[i]) != SIGN(a[i - 1])) {
            maxlen = std::max(maxlen, len);
            len = 0;
        } else {
            if (i == a.size() - 1)
                return std::max(maxlen, len + 1);
        }
    }

#undef SIGN

    return maxlen;
}


Can you please give me tips to improve my code?
A small portability bug: std::size_t is in the std namespace, assuming it's declared by including &lt;cstddef&gt; (recommended).

No unit tests are included, but I'd expect one that tests that the result is zero when the input collection is empty.  We need to initialize maxlen to zero for that test to pass.

When comparing consecutive elements of a collection, always consider using std::adjacent_find().  With a suitable predicate function, we can find changes from negative to non-negative and vice versa without needing to code our own loop or do any indexing.

(More advanced) Consider making your algorithm generic, templated on an iterator type, so that it can be applied to any collection (or even to an input stream directly).

Here's a version that applies all of these suggestions (and some from other answers that I've not repeated above):

#include &lt;algorithm&gt;
#include &lt;cmath&gt;
#include &lt;cstddef&gt;
#include &lt;iterator&gt;

template&lt;typename ForwardIt&gt;
std::size_t getLongestSameSignSequenceLength(ForwardIt first, ForwardIt last)
{
    auto const signdiff =
        [](auto a, auto b){ return std::signbit(a) != std::signbit(b); };

    std::size_t maxlen = 0;

    while (first != last) {
        ForwardIt change = std::adjacent_find(first, last, signdiff);
        if (change != last) { ++change; }

        std::size_t len = std::distance(first, change);
        if (len &gt; maxlen) { maxlen = len; }

        first = change;
    }

    return maxlen;
}


// tests:

#include &lt;vector&gt;

int main()
{
    struct testcase { std::size_t expected; std::vector&lt;int&gt; inputs; };
    std::vector&lt;testcase&gt; tests
        {
         {0, {}},
         {1, {1}},
         {1, {1, -2}},
         {1, {1, -2,  3}},
         {1, {-1, 2, -3}},
         {2, {1,  2}},
         {2, {1,  2, -3}},
         {2, {-1, -2, 3}},
         {2, {-1, 2,  3}},
         {2, {-1, 2,  3, -4}},
        };

    int failures = 0;
    for (auto const&amp; [e, v]: tests) {
        failures += getLongestSameSignSequenceLength(v.begin(), v.end()) != e;
    }

    return failures;
}