使用函数作为'for'循环的第二个参数

Using a function as the second argument of a 'for' loop

本文关键字:循环 第二个 参数 for 函数      更新时间:2023-10-16

让我们假设我有以下代码:

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.
}