在c ++ 11中,您可以遍历带有range for循环的容器:
for (auto i : vec) { /* do stuff */ }
Run Code Online (Sandbox Code Playgroud)
除了反向迭代不那么明显(C++ 11基于反向范围的for循环)的缺点之外,它还受到无法为迭代定义自定义步骤这一事实的限制.
有办法吗?我无法理解它,但想象一下适配器
template<typename T>
struct step
{
T const &container;
step( T const &cont, int aStep);
// provide begin() / end() member functions
// maybe overload the ++ operator for the iterators ?
};
for (auto i : step(vec, i)) {}
Run Code Online (Sandbox Code Playgroud)
编辑:
讨论是关于实现类似于Pythons生成器https://wiki.python.org/moin/Generators的语义,例如range()函数.请不要对这会如何增加代码复杂性做出毫无意义的评论,没有人回过头来编写Python中的循环,尽管在C++中并非如此(我应该再说一遍:情况并非如此)在c ++)我想探索写作方式
for (auto i : range(vec, step))
Run Code Online (Sandbox Code Playgroud)
因为新标准提供了使用这种语法的工具.range()函数将是一次性的努力,代码的用户不必担心imlpementation的细节
在C++中,可以在类中初始化类的字段的值,如:
class X
{
int a = 5;
}
Run Code Online (Sandbox Code Playgroud)
它是什么原因?它有用吗?默认的ctor完全相同.似乎我无法使用位掩码(int a : 3)初始化值.
我很抱歉,如果这是怎样的一个愚蠢的问题,但我是新来的C++和真的不能找到答案;
当我使用时rand(),我当然必须首先使用srand().
起初我只是导入<ctime>和做srand(time()),这有效.但如果我rand()不止一次打电话- 经常time()发生变化 - 那么我会得到同样的答案.所以例如;
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
bool x = true;
while(x == true)
{
int num = 1;
srand(time(NULL));
num = rand();
cout<<num%10<<endl;
}
}
Run Code Online (Sandbox Code Playgroud)
可能会产生类似的东西,如6666666666777777777700000000003333333333
哪个对我的目的没有好处 - 我更喜欢像163509284749301935766这样的东西.
我正在观看Bjarne Stroustrup的演讲" The Essential C++ ".
在Q&A会话中,关于如何管理繁重的模板编程代码,他提到:"通过constack perfunction,您可以基本上消除每个通过编写普通代码生成值的模板元编程".
该constack perfunction只是通过声音胡乱猜测.
请问这项技术的正确用语是什么?所以我可以做一些跟进阅读.
更新:只需将标题修改为"constexpr功能".
我找到了这段代码,并想知道我是否真的应该在我的真实项目中实现这样的东西.
令我困惑的事情是
这需要更多的编译时间,但我不应该以运行时为代价来打扰编译时间.
如果N真的是一个非常大的数字呢?源代码中是否有文件大小限制?
或者它的好事要知道,而不是实施?
#include <iostream>
using namespace std;
template<int N>
class Factorial {
public:
static const int value = N * Factorial<N-1>::value;
};
template <>
class Factorial<1> {
public:
static const int value = 1;
};
int main() {
Factorial<5L> f;
cout << "5! = " << f.value << endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
5! = 120
Run Code Online (Sandbox Code Playgroud)
稍微修改一下,因为我正在玩代码,发现了
Factorial<12> f1; // works
Factorial<13> f2; // doesn't work
Run Code Online (Sandbox Code Playgroud)
错误:
undefined reference to `Factorial<13>::value'
Run Code Online (Sandbox Code Playgroud)
是不是可以12进一步深入?