Use c ++ 11 to create a range and pythonrange similar to python.

Source: Internet
Author: User

Use c ++ 11 to create a range and pythonrange similar to python.

The range Function in python represents a continuous ordered sequence, which is very convenient to use, because the initialization process is hidden during definition, because only the begin () and end () or only one end () can represent a continuous sequence. You can also specify the step size generated by the sequence, for example, the sequence generated by range (, 8) is [0, 8], the default step size is 1, range (3) indicates the sequence [0, 1, 2]. The traversal of range is also very convenient:

for i in range(3):    print i

  

In c ++ 11, a new feature range-based for loop is added. In fact, this is not a new feature. It is already available in languages such as c #, java, and python. This loop method is very concise. In fact, it encapsulates the traversal of the traditional in ()/end () method, which is a syntactic sugar of the loop. Easy to use:

// Traverse vectorstd: vector <int> v; for (auto I: v) {cout <I <endl;} // traverse mapstd :: map <string, int> map; for (const auto & item: map) {cout <item-> first <item-> second <endl ;}

The interesting thing about the range-based for loop in c ++ 11 is that it supports the traversal of custom types, but it requires that the custom types meet three conditions:

After these three conditions are met, the custom type can support the range-based for loop.

Back to the python range () mentioned earlier, it is very useful, but there is nothing similar in c ++, although many containers in the standard library, such as vector, list, queue, map, initialization list, and array, all support the range-based for loop, they are not easy to use, for example, to generate an ordered sequence, you need to initialize it. If there is something similar to python range, it will be perfect. Although c ++ 11 is not available now, we can use c ++ 11 to implement a similar range, and I want to make this range more powerful than python's range, let it not only support integers but also floating point numbers, but also two-way iteration. It is relatively simple to implement this range. Let's take a look at the specific implementation:

namespace Cosmos{    template<typename value_t>    class RangeImpl    {        class Iterator;    public:        RangeImpl(value_t begin, value_t end, value_t step = 1) :m_begin(begin), m_end(end), m_step(step)        {            if (step>0&&m_begin >= m_end)                throw std::logic_error("end must greater than begin.");            else if (step<0 && m_begin <= m_end)                throw std::logic_error("end must less than begin.");            m_step_end = (m_end - m_begin) / m_step;            if (m_begin + m_step_end*m_step != m_end)            {                m_step_end++;            }        }        Iterator begin()        {            return Iterator(0, *this);        }        Iterator end()        {            return Iterator(m_step_end, *this);        }        value_t operator[](int s)        {            return m_begin + s*m_step;        }        int size()        {            return m_step_end;        }    private:        value_t m_begin;        value_t m_end;        value_t m_step;        int m_step_end;        class Iterator        {        public:            Iterator(int start, RangeImpl& range) : m_current_step(start), m_range(range)            {                m_current_value = m_range.m_begin + m_current_step*m_range.m_step;            }            value_t operator*() { return m_current_value; }            const Iterator* operator++()            {                m_current_value += m_range.m_step;                m_current_step++;                return this;            }            bool operator==(const Iterator& other)            {                return m_current_step == other.m_current_step;            }            bool operator!=(const Iterator& other)            {                return m_current_step != other.m_current_step;            }            const Iterator* operator--()            {                m_current_value -= m_range.m_step;                m_current_step--;                return this;            }        private:            value_t m_current_value;            int m_current_step;            RangeImpl& m_range;        };    };    template<typename T, typename V>    auto Range(T begin, T end, V stepsize)->RangeImpl<decltype(begin + end + stepsize)>    {        return RangeImpl<decltype(begin + end + stepsize)>(begin, end, stepsize);    }    template<typename T>    RangeImpl<T> Range(T begin, T end)    {        return RangeImpl<T>(begin, end, 1);    }    template<typename T>    RangeImpl<T> Range(T end)    {        return RangeImpl<T>(T(), end, 1);    }}

Let's look at the test code:

void TestRange(){    cout << "Range(15):";    for (int i : Range(15)){        cout << " " << i;    }        cout << endl;    cout << "Range(2,6):";    for (int i : Range(2, 6)){        cout << " " << i;    }    cout << endl;    cout << "Range(10.5, 15.5):";    for (float i : Range(10.5, 15.5)){        cout << " " << i;    }    cout << endl;    cout << "Range(35,27,-1):";    for (int i : Range(35, 27, -1)){        cout << " " << i;    }    cout << endl;    cout << "Range(2,8,0.5):";    for (float i : Range(2, 8, 0.5)){        cout << " " << i;    }    cout << endl;    cout << "Range(8,7,-0.1):";    for (auto i : Range(8, 7, -0.1)){        cout << " " << i;    }    cout << endl;    cout << "Range('a', 'z'):";    for (auto i : Range('a', 'z'))    {        cout << " " << i;    }    cout << endl;}

Test results:

We can see that this range not only generates an ordered sequence based on the step size, but also supports floating point, char, and bidirectional iteration, which is more powerful than python's range.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.