我想听听您关于BOOST_FOREACH
.
我已经阅读了它,就性能而言,它并不是一个非常重的标题。
此外,它强制使用“break”和“continue”语句,因为您不能真正拥有由布尔值驱动的退出条件,而且我一直被告知应尽可能避免使用“break”和“continue”。
当然,优点是您不直接处理迭代器,这简化了迭代容器的任务。
你怎么看待这件事?
你认为如果使用它应该被系统地采用以保证项目中的同质性,还是只在某些情况下才推荐使用它?
我想听听您关于BOOST_FOREACH
.
我已经阅读了它,就性能而言,它并不是一个非常重的标题。
此外,它强制使用“break”和“continue”语句,因为您不能真正拥有由布尔值驱动的退出条件,而且我一直被告知应尽可能避免使用“break”和“continue”。
当然,优点是您不直接处理迭代器,这简化了迭代容器的任务。
你怎么看待这件事?
你认为如果使用它应该被系统地采用以保证项目中的同质性,还是只在某些情况下才推荐使用它?
我会说基于 C++ 范围的循环取代了它。这相当于这个 BOOST_FOREACH 示例:
std::string hello( "Hello, world!" );
for (auto c : hello)
{
std::cout << c;
}
我从来没有发现我需要在 ++03 中使用它。
请注意,在复制元素昂贵的容器上或在通用上下文中使用基于范围的循环时,最好使用const&
这些元素:
SomeContainerType<SomeType> v = ....;
for (const auto& elem : v)
{
std::cout << elem << " ";
}
同样,如果您需要修改容器的元素,则使用非常量 & ( auto& elem : v
)。
In programming, clarity is trump. I've always used boost foreach in C++03, found it much more readable than the hand-written loop, the header size won't kill you. As @juanchopanza rightly noted, of course, this question is obsolete in C++11.
Your concerns with break and continue are unfounded and probably counterproductive. With the traditionally long for-loop headers of C++03, people tend to not read the loop header and to overlook any condition variables that hide in the loop header. Better make your intent explicit with break and continue.
If you have decided to use boost foreach, use it systematically. It is supposed to be used to replace the bread-and-butter loops, after all.
我刚刚用一个简单的 for 循环替换了 BOOST_FOREACH 的使用,并获得了 50% 的加速,所以我会说它绝对不是最好的使用方法。您也不会得到有时您实际需要的循环计数器(例如“i”)。就我个人而言,我不是 YMMV 的粉丝,如果它更适合你的风格的话。
顺便说一句 - “沉重的标题”不会影响程序的性能,只会影响编译时间。