C ++ 11基于范围的for循环:如何忽略值? [英] C++11 range-based for loop: how to ignore value?
问题描述
我有一个C ++容器,我想运行一个循环与容器中的元素相同的次数。但是我不关心循环中容器中的值。例如:
I have a C++ container and I want to run a loop the same number of times as there are elements in that container. But I do not care about the values in the container during the loop. For example:
for (const auto& dummy : input) {
cout << '.';
}
唯一的问题是 dummy
是一个未使用的变量,我已经指示编译器禁止这些。
The only problem is, dummy
is an unused variable and I have instructed the compiler to prohibit those.
我想出的两个不起眼的解决方法是说 void)dummy; c>在循环体中使沉默编译器,或者使用旧式for循环从0到
distance(begin(input),end(input)
Two inelegant solutions I have come up with are to say (void)dummy;
in the loop body to silence the compiler, or to use an old-style for loop from 0 to distance(begin(input), end(input))
.
我尝试省略变量名,但没有编译(没有大惊喜)。
I tried omitting the variable name but that failed to compile (no big surprise).
我正在使用GCC 4.7.2。
I'm using GCC 4.7.2.
推荐答案
如果你实际想要执行的操作是你在你的例子中写的一个简单的一个,一个更好的方式来实现你想要的是:
If the operation that you actually want to perform is the trivial one that you wrote in your example, a much better way to achieve what you want is:
std::cout << std::string{boost::distance(input), '.'};
否则,如果你只想循环一个范围并对每个元素执行操作,忽略元素值, for_each
< algorithm>
正是你想要的。
Otherwise, if you just want to loop over a range and perform an operation for each element, ignoring the element value, the for_each
<algorithm>
is exactly what you want.
-
使用boost:
Using boost:
#include <boost/range/algorithm.hpp>
boost::for_each(input, [](auto&& /*ignored*/) { /* do stuff */; });
使用STL:
Using the STL:
#include <algorithm>
std::for_each(std::begin(input), std::end(input), [](auto&& /*ignored*/) {
/* do stuff */;
});
请注意, c $ c> break 或 continue
,但你可以 return
行为。
Note that within the lambda you cannot break
or continue
, but you can return
early to achieve the same behavior.
仍然,你应该看看另一个 STL算法,并选择与您的意图最匹配的那个(通常也是最快的)。
Still, you should take a look at the other STL algorithms and choose the one that matches your intent best (it will generally also be the fastest).
这篇关于C ++ 11基于范围的for循环:如何忽略值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!