使用函数作为'for'循环的第二个参数
Using a function as the second argument of a 'for' loop
让我们假设我有以下代码:
for(std::vector<int>::iterator i = vect.begin(); i != vect.end(); ++i)
{
//do smth here
}
vect.end()是否会在每次迭代中被重新调用?如果是,那么我应该如何迭代向量?
在逻辑表达式(for循环的第二个参数)内部调用函数通常是不好的做法?
是的,会的。然而,如果编译器能够确定vect.end()
返回的值永远不会改变,那么它当然可以对其进行优化。然而,如果你确实想避免这样做,只需将代码更改为:
for(std::vector<int>::iterator i = vect.begin(), end = vect.end();
i != end; ++i)
{
//do smth here
}
当然,您应该确保您的代码不依赖于在每次迭代中检查end()
。例如,如果对向量中的元素执行vect.erase(i)
,则需要确保每次都获得新的end()
迭代器(还需要确保将erase
的结果分配给i
)。
您所拥有的似乎非常好。vect.end()
应该是一个O(1)运算,所以这不会对性能造成很大影响。
但如果你正在寻找替代方案:
typedef std::vector<int>::iterator iter;
iter end = vect.end();
for(iter it = vect.begin(); it != end; ++it) {
}
这没什么错。
或:
std::vector<int>::iterator it = vect.begin();
std::vector<int>::iterator end = vect.end();
for(it; it != end; it++) ...
或者,如果您的编译器支持基于C++11范围的for循环,您可以像这样迭代向量:
for(auto x : vect)
{
//x is the actual int, not an iterator.
}
相关文章:
- 为什么程序运行时我的第二个循环不执行?
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- 当通过tcp接收编码图像的消息时,zmq在第二个循环中崩溃
- 第二个 while 循环未运行,将值设置为 "nan"
- 为什么在我的程序中的第二个循环时,当它在循环之前循环时不起作用
- 如何在我的代码中修复无穷循环?我认为它跳过了第二个CIN,因此它一直在循环
- 如何在C 循环中找到第二个最大数字
- 虽然循环在第二个循环上不起作用
- 为什么第一个循环的剂量总是比第二个循环快
- 嵌套如果循环跳到第二个,即使第一个不为真
- 为什么我的程序在循环时不会重新进入第二个?C
- 为什么 for 循环没有达到循环的第二个条件中设置的数字
- 无法获得第二个正确循环
- C++字符串流如何在第二个循环中重置它
- 第二个无效响应在我的验证循环中被接受
- 而循环在第二个用户输入C++后停止工作
- 如何在for循环中声明第二个迭代器
- 我的 for 循环第一次正确输入,但第二次不正确,并显示第二个输入的输出。我不明白为什么会这样。
- For循环多个变量,第二个变量不更新
- 程序忽略第二个循环