在C++中缩写 for 循环
Abreviating the for loop in C++
最近,在编码时,我发现自己一遍又一遍地编写完全相同的循环标头:
for (int i = 0; i < [somevalue]; i++)
{
[other code]
}
有没有人知道一种方法来重载 for 循环,或者定义另一个关键字,以便它接受一个数字并通过给定的 for 循环将其馈送,将 for 缩写为如下所示的内容:
for ([somevalue])
{
[other code]
}
或
nfor ([somevalue])
{
[other code]
}
因为一直编写for(12)
并让它遍历代码 12 次会更好
您可以创建自己的for
方法,该方法采用函数对象:
template <class F>
void for_t(std::size_t n, F const& f)
{
while (n--)
f();
}
int main()
{
int count = 0;
for_t(5, [&] { std::cout << ++count << " "; });
}
或者使用范围(和提升):
for(int i : boost::counting_range(0, limit))
/* do nice things */ ;
提升::counting_range
或者
,如果你想使用普通的旧宏,可以做
#define nfor(somevalue) for(int i = 0; i < somevalue; ++i)
然后将其用作
nfor(10)
{
cout << "Hello World " << i << "!" << endl;
}
class until {
public:
until(int limit) : count(limit) {}
int operator*() const { return count; }
until &operator++() { ++count; return *this; }
bool operator!=(const until &rhs) const { return count != rhs.count; }
until begin() const { return 0; }
until end() const { return count; };
private:
int count;
};
#include <iostream>
int main() {
for (int count : until(5)) {
std::cout << count << ' ';
}
}
N3853:基于范围的for-loops,下一代将使for
更紧凑。
例如喜欢
template< class Func >
void repeat( int const n, Func const& f )
{
for( int i = 1; i <= n; ++i ) { f(); }
}
void foo()
{
int n = 1;
repeat( 12, [&]
{
// other code, e.g.
cout << n++ << endl;
} );
}
免责声明:编译器的手未触及代码。
如果您喜欢宏方法,最好稍微调整一下@vsoftco的解决方案,以便为循环控制变量使用不同的名称:
#define nfor(varname, somevalue) for(int varname = 0; varname < somevalue; ++varname)
这样,您可以使用上面的宏嵌套 for 循环:
nfor(i, 10)
{
nfor(j, 10)
{
cout << i << " " << j;
}
}
这在 C++ 中的 for 循环中是不可能的。有两种方法可以做你想做的事。
第一种是使用 C++11 中引入的 for loop 系列的最新成员。
for(int x : (int[12]){}){
// Do stuff
}
不是你想要的,但仍然短一点。另一种选择是创建自己的函数,并让它采用大小和函数。0x499602D2在这方面击败了我,所以请参阅他们的帖子了解如何做到这一点。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式