C++11中自定义range

python中的range功能非常好用

for i in range(100):
    print(i)

现在利用C++11的基于范围的for循环特性实现C++中的range功能

class range
{
public:
	range(int end)
	{
		_begin = 0;
		_end = end;
		_step = 1;
	}
	range(int begin, int end, int step=1)
	{
		_begin = begin;
		_end = end;
		_step = step;
		if (!_step) // 步长为0, 设为默认值1
			_step = 1;
	}


	class iterator
	{
	public:
		iterator(int x, int s=1)
		{
			n = x;
			step = s;
		}

		iterator &operator++()
		{
			n += step;
			return *this;
		}

		bool operator!=(const iterator &x)
		{
			return (step>0)? n<x.n : n>x.n;
		}

		int &operator*()
		{
			return n;
		}

	private:
		int n, step;
	};

	iterator begin()
	{
		return iterator(_begin, _step);
	}
	iterator end()
	{
		return iterator(_end, _step);
	}

private:
	int _begin, _end, _step;
};

例:

for(auto i: range(10))
    std::cout << i << std::endl;

for(auto i: range(10, 100))
    std::cout << i << std::endl;

for(auto i: range(10, 100, 2))
    std::cout << i << std::endl;

for(auto i: range(100, 10, -2))
    std::cout << i << std::endl;
posted @ 2016-12-19 23:26  electron  阅读(995)  评论(0编辑  收藏  举报