我有一个序列,例如
std::vector< Foo > someVariable;
Run Code Online (Sandbox Code Playgroud)
我想要一个循环遍历其中的所有内容.
我能做到这一点:
for (int i=0;i<someVariable.size();i++) {
blah(someVariable[i].x,someVariable[i].y);
woop(someVariable[i].z);
}
Run Code Online (Sandbox Code Playgroud)
或者我可以这样做:
for (std::vector< Foo >::iterator i=someVariable.begin(); i!=someVariable.end(); i++) {
blah(i->x,i->y);
woop(i->z);
}
Run Code Online (Sandbox Code Playgroud)
这些似乎都涉及相当多的重复/过度打字.在理想的语言中,我希望能够做到这样的事情:
for (i in someVariable) {
blah(i->x,i->y);
woop(i->z);
}
Run Code Online (Sandbox Code Playgroud)
似乎迭代顺序中的所有内容将是一个非常常见的操作.有没有办法做到这一点,代码不是它应该的两倍长?
我有这个程序需要2.34秒才能运行,gprof表示它只需要1.18秒.我已经在其他地方读过答案,建议如果例如程序受I/O限制,gprof可能会出错,但这个程序显然不是.
这也适用于我试图描述的有用程序.这不是特定于这个琐碎的测试用例.
(同样在这种情况下,gprof表示main()占用了程序运行时间的100%以上,这是一个非常愚蠢的错误但不会给我带来麻烦.)
$ cat test.c
int main() {
int i;
for (i=0;i<1000000000;i++);
}
$ gcc test.c -o test
$ time ./test
real 0m2.342s
user 0m2.340s
sys 0m0.000s
$ gcc test.c -o test -pg
$ time ./test
real 0m2.342s
user 0m2.340s
sys 0m0.000s
$ gprof test |head
Flat profile:
Each sample counts as 0.01 seconds.
% cumulative self self total
time seconds seconds calls Ts/call Ts/call name
101.33 1.18 1.18 main
% the percentage of the total running time of …Run Code Online (Sandbox Code Playgroud)