Joh*_*nck 5 c++ for-loop c++11
我有一个C++容器,我想运行一个循环的次数与该容器中的元素相同.但我不关心循环期间容器中的值.例如:
for (const auto& dummy : input) {
cout << '.';
}
Run Code Online (Sandbox Code Playgroud)
唯一的问题是,dummy是一个未使用的变量,我已指示编译器禁止这些.
我提出的两个不优雅的解决方案是(void)dummy;在循环体中说要使编译器静音,或者使用从0到0的旧式for循环distance(begin(input), end(input)).
我尝试省略变量名但无法编译(没什么大惊喜).
我正在使用GCC 4.7.2.
不需要显式循环.
use std::begin;
use std::end;
std::cout << std::string(std::distance(begin(input), end(input)), '.');
Run Code Online (Sandbox Code Playgroud)
或者在非通用上下文中:
std::cout << std::string(input.size(), '.');
Run Code Online (Sandbox Code Playgroud)
如果你想在循环中做一些更复杂的事情,那就去吧(void)dummy;.它很清楚,众所周知并且有效.
还看看<algorithm>; 您正在实施的内容可能会更好地实现这些功能.C++ Seasoning是一个很好的谈论.
如果您实际想要执行的操作是您在示例中编写的简单操作,那么实现您想要的效果的更好方法是:
std::cout << std::string{boost::distance(input), '.'};
Run Code Online (Sandbox Code Playgroud)
否则,如果您只想循环一个范围并对每个元素执行操作,忽略元素值,那么这for_each <algorithm>正是您想要的。
使用升压:
#include <boost/range/algorithm.hpp>
boost::for_each(input, [](auto&& /*ignored*/) { /* do stuff */; });
Run Code Online (Sandbox Code Playgroud)使用STL:
#include <algorithm>
std::for_each(std::begin(input), std::end(input), [](auto&& /*ignored*/) {
/* do stuff */;
});
Run Code Online (Sandbox Code Playgroud)请注意,在 lambda 中您不能使用breakor continue,但您可以return尽早实现相同的行为。
尽管如此,您还是应该看看其他STL 算法,并选择最符合您意图的算法(通常也是最快的)。
| 归档时间: |
|
| 查看次数: |
1666 次 |
| 最近记录: |