C ++ for循环语法短

时间:2016-07-13 17:30:34

标签: c++ c++11 for-loop macros

我想编写一个简短的for循环(有或没有宏),通过猜测起点是否小于或大于(或等于)终点来起作用,如下所示:

fr(i = 0 .. 3) printf("%d ", i)
    output: 0 1 2 3

fr(i = 8 .. 3) printf("%d ", i)
    ouput: 8 7 6 5 4 3

fr(i = 3 ..< 6) printf("%d ", i)
    output: 3 4 5

fr(i = 5 ..> 1) printf("%d ", i)
    output: 5 4 3 2

简而言之,我想以一种简短的方式写一篇强大的内容......这可能吗?

如果不是,还有另一种方法吗?

2 个答案:

答案 0 :(得分:1)

这与您的预期非常接近:

#include <iostream>
#include <algorithm>

#define LT -1 +
#define GT 1 +
#define FR(type, var, from, to) for(type dir = (from < to)? 1: -1, i = from; i != to + dir; i += dir)

int main() {
    FR(int, i, 0, 3) std::cout << i << " ";
    std::cout << std::endl;

    FR(int, i, 8, 3) std::cout << i << " ";
    std::cout << std::endl;

    FR(int, i, 3, LT 6) std::cout << i << " ";
    std::cout << std::endl;

    FR(int, i, 5, GT 1) std::cout << i << " ";
    std::cout << std::endl;
}

答案 1 :(得分:0)

如果你假设所有的值都是整数,那么这样的东西可能会起作用:

#define MYFOR(i,a,b) for (int i = (a); i != (b); i = (a)<(b)? i+1 : i-1)

然后使用就是这样:

MYFOR(i, 0, 10) printf("%d ", i);
MYFOR(i, 5, 0) printf("%d ", i);