Implementing range from_to with step #include &lt;vector&gt;

std::vector&lt;int&gt; Range(int from, int to, int step = 1) {
    std::vector&lt;int&gt; range;

    if (step &gt; 0) {
        for(int i = from; i &lt; to; i += step) {
            range.push_back(i);
        }
    } else if (step &lt; 0) {
        for(int i = from; i &gt; to; i += step) {
            range.push_back(i);
        }
    }

    return range;
}

I don't like code duplication in my implementation, because I have two almost identical blocks.
Is it possible to avoid it?
I think the easiest way to solve this is to first calculate how many steps it takes to go from from to to, and then just build an array of that many elements. That also has the advantage that you can reserve the right amount of elements in the vector up front. You also have to make sure that step has the correct sign.
if (from &lt;= to != step &gt; 0)
    step = -step;

size_t distance = std::abs(to - from);
size_t stepsize = std::abs(step);
size_t nsteps = (distance + stepsize - 1) / stepsize;

std::vector&lt;int&gt; range;
range.reserve(nsteps);

for (size_t i = 0; i &lt; nsteps; ++i)
    range.push_back(from + i * step);

You also might want to add some check that step is not zero.