BOOST_FOREACH和c ++ 11之间区别循环的区别? [英] Difference between BOOST_FOREACH and c++11 for range based loop?
问题描述
-
BOOST_FOREACH
和c ++ 11基于范围的循环之间的主要区别是什么? - 是否有特定的情况,我想使用
BOOST_FOREACH
而不是基于范围的循环,反之亦然? b
$ b在用
std :: vector
执行一个小测试后,用1,000,000int
变量我发现BOOST_FOREACH
比基于范围的循环慢了一点(比基于范围的循环长1.25倍)。
解决方案主要区别在于range-for是一种语言结构,而
BOOST_FOREACH
是一个在引擎盖下做很多魔术的宏来做一些看起来像那个语言结构的东西。它正在尝试与Pre-C ++ 11的局限性做同样的事情。BOOST_FOREACH
的目标是 range-for。
有一种情况我甚至想用
BOOST_FOREACH
代替range-for,它是迭代你想展开元组的元组容器:
std :: map< int,int>米;
int key,value;
BOOST_FOREACH(boost :: tie(key,value),m)
{
//在这里用键和值做某事
}
$ c $
$int key ,价值;
for(const auto& pair:m)
{
std :: tie(key,value)= pair;
//做点什么
}
我喜欢你可以把
tie
直接放到循环头文件中,尽管最终这是一个小小的优势,甚至几乎不值得把它当作一个决定。使用范围。总是。
C ++ 17将会介绍结构化绑定,它甚至可以消除这个小句法优势:
for(auto const& [key,value]:m)
{
//做某事
}
此时,没有任何理由使用
BOOST_FOREACH
。- What are the main differences between
BOOST_FOREACH
and c++11 range based loop? - Is there a specific situation where I would want to use
BOOST_FOREACH
instead of range based loop or vice versa?
After executing a little test with
std::vector
filled with 1,000,000int
variables I found out thatBOOST_FOREACH
is a little bit slower than range based loop (took about 1.25 times longer than for a ranged based loop).解决方案The main difference is that range-for is a language construct, while
BOOST_FOREACH
is a macro doing lots of magic under the hood to do something that looks like that language construct. It is trying to do exactly the same thing with the limitations of pre-C++11. The goal ofBOOST_FOREACH
is range-for.There is exactly one situation where I would even think of using
BOOST_FOREACH
instead of range-for, and it is iterating over a container of tuples where you want to unroll the tuple:std::map<int, int> m; int key, value; BOOST_FOREACH(boost::tie(key, value), m) { // do something with key and value here }
as compared to:
int key, value; for (const auto& pair : m) { std::tie(key, value) = pair; // do something }
I like that you can put the
tie
directly into the loop header, although ultimately that's such a minor advantage that it's hardly worth even considering this as being a decision. Use range-for. Always.
C++17 will introduce structured bindings, which remove even that minor syntactical advantage:
for (auto const& [key, value] : m) { // do something }
At that point, there will be no reason whatsoever to use
BOOST_FOREACH
.这篇关于BOOST_FOREACH和c ++ 11之间区别循环的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- What are the main differences between