Hi! Hope you're enjoying this blog. I have a new home at www.goldsborough.me. Be sure to also check by there for new posts <3

Thursday, April 2, 2015

Python's built-in range() function in C++

Not that I don't appreciate the differences between Python and C++, but ...

class range
{
    
public:
    
    typedef std::vector<long>::iterator iterator;
    
    typedef std::vector<long>::const_iterator const_iterator;
    
    range(long end)
    : range(0, end)
    { }
    
    range(long begin, long end, long step = 1)
    {
        long diff = end - begin;
        
        if ((diff > 0 && step > 0) ||
            (diff < 0 && step < 0))
        {
            while(begin != end)
            {
                range_.push_back(begin);
                
                begin += step;
            }
        }
    }
    
    iterator begin()
    {
        return range_.begin();
    }
    
    const_iterator begin() const
    {
        return range_.begin();
    }
    
    iterator end()
    {
        return range_.end();
    }
    
    const_iterator end() const
    {
        return range_.end();
    }
    
private:
    
    std::vector<long> range_;
};

int main(int argc, char * argv [])
{
    for (auto i : range(10, 5, -1))
    {
        std::cout << i << std::endl;
    }
}


Output:

10
9
8
7
6

Maybe not that much shorter, but certainly nicer than your usual way of iterating over a range:

for (std::size_t i = 10; i > 5; --i)
{
    std::cout << i << std::endl;
}

kthxbye

No comments :

Post a Comment