Use c++11 to create a python-like range

Source: Internet
Author: User

Source: http://www.cnblogs.com/qicosmos/p/3540435.html

The range function in Python represents a contiguous sequential sequence, and the range is handy because the initialization process is implied when it is defined, because it only needs to give begin () and end () or just one end () to represent a sequential sequence. You can also specify the step that the sequence produces, such as the sequence produced by range (0,10,8) to [0, 8], and the default step of 1,range (3) for the sequence that is [0,1,2]. The traversal of range is also convenient:

For I in range (3):    Print I

  

C++11 adds a new feature to the range-based for loop, which is not something new in the language of C #, Java, and Python. This circular way is very concise, it is in fact the traditional begin ()/end () way of the traversal of the packaging, is considered a circular syntax sugar. The usage is simple:

Traverse vectorstd::vector<int> v;for (auto i:v) {    Cout<<i<<endl;} Traverse mapstd::map<string in read-only mode, int> map;for (const auto& item:map) {    cout << item->first<< Item->second<<endl;}

The interesting thing about C++11 's range-based for loop is that he can support the traversal of custom types, but requires that custom types meet three criteria:

    1. To implement begin () and end (), they are used to return iterators for the first and last elements, respectively;
    2. Provide an iterative termination method;
    3. Provides a way to traverse range;

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

Back to the Python range you just mentioned, it works, but there is no such thing in C + +, although there are many containers in the standard library such as vectors, list, queue, map, initialization list, and array, all of which already support range-based For loops, but they are not easy to use, for example, to generate an ordered sequence, a special initialization is required, and if there is something like Python range, it is perfect. Although C++11 is not now, we can use C++11 to achieve a similar range, and I want to make this range more powerful than the Python range, so that it can support not only integers but also floating-point numbers, as well as bidirectional iterations, The implementation of this range is relatively simple, see 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_tM_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_ran            GE (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_curre            Nt_step; } bool Operator!= (const iterator& Other) {return m_current_step! = Other.m_curre            Nt_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 + s)    Tepsize) > {return rangeimpl<decltype (begin + END + stepsize) > (Begin, End, stepsize); } template<typename t> rangeimpl<t> Range (t begin, T end) {return rangeimpl<t> (begin, E    nd, 1);    } template<typename t> rangeimpl<t> Range (t end) {return rangeimpl<t> (t (), end, 1); }}

Look at the test code again:

 void testrange () {cout << "Range (15):";    for (int i:range ()) {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 (+,-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:

You can see that this range not only produces ordered sequences based on stride size, but also supports floating-point types and char types as well as bidirectional iterations, which is more powerful than Python's range.

If you think this article is useful for you, you can click on the recommendation, thank you.

C++11 Boost Technical Exchange Group: 296561497, Welcome to Exchange technology.

Use c++11 to create a python-like 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.