你可以尝试定义以下宏:
#define for_range(_type, _param, _A1, _B1) \
for (_type _param = _A1, _finish = _B1,\
_step = static_cast<_type>(2*(((int)_finish)>(int)_param)-1),\
_stop = static_cast<_type>(((int)_finish)+(int)_step); _param
_param = static_cast<_type>(((int)_param)+(int)_step))
现在你可以使用它:
for_range (unsigned, i, 10,0)
{
cout << "backwards i: " << i << endl;
}
它可以用于无符号整数、枚举和字符的正向和反向迭代:
for_range (char, c, 'z','a')
{
cout << c << endl;
}
enum Count { zero, one, two, three };
for_range (Count, c, zero, three)
{
cout << "forward: " << c << endl;
}
尽管它的定义有些笨拙,但它被优化得非常好。我在VC++中查看了反汇编器。
代码非常高效。不要被三个for语句吓到:编译器在优化后只会产生一个循环!你甚至可以定义嵌套循环:
unsigned p[4][5];
for_range (Count, i, zero,three)
for_range(unsigned int, j, 4, 0)
{
p[i][j] = static_cast<unsigned>(i)+j;
}
显然,您无法遍历具有间隔的枚举类型。