zoukankan      html  css  js  c++  java
  • 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;
    
  • 相关阅读:
    ESB企业服务总线
    OpenStack的架构详解[精51cto]
    用MSBuild和Jenkins搭建持续集成环境(1)[收集]
    Hmac算法
    自定义JDBCUtils工具类
    读取JDBC配置文件的二种方式
    哈希算法
    BouncyCastle
    签名算法
    3种查看java字节码的方式
  • 原文地址:https://www.cnblogs.com/electron/p/6201030.html
Copyright © 2011-2022 走看看