按照 TopCoder 上的 Dmitry Korolev 教程,我遇到了这个通用容器遍历宏:
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
它让我感到困惑,因为它似乎缺少括号。在解释中他说 typeof(...) 被表达式的类型 (...) 取代,这让我对这个遍历宏更加困惑(因为我的直觉看到 typeof (x ; y ; z) 和不会 工作因为 x;y;z 不是表达式,即使它工作 typeof(...) 也会“吃掉”(...))。
有用吗?为什么?
最佳答案
#define tr(container, it) \
for(typeof(container.begin()) it = container.begin(); \
it != container.end(); \
it++
)
这就是he has written这在语法上是正确的。顺便说一句,typeof
是一个 gcc 扩展,不会在其他编译器中工作。
如果您的编译器支持 C++0x,您可能需要使用 auto
例如,相同的宏可以用 C++0x 编写为
#define tr(container, it) \
for(auto it = container.begin(); \
it != container.end(); \
it++
)
关于c++ - 这段代码(用于容器遍历的宏)是否有效?如果是,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415818/