我正在尝试使用 C++ 中的每个循环。
this->Functions 是一个 vector 。
std::vector< std::shared_ptr<Sum_Function> > Functions;
阅读后我发现了两种不同的方法。
bool Container::HasFunction(std::string stdstrFunctionName )
{
for (auto &func : this->Functions)
{
if (func->getFunctionName() == stdstrFunctionName)
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////////
bool Container::HasFunction(std::string stdstrFunctionName )
{
for (auto it = this->Functions.begin(); it != this->Functions.end(); ++it)
{
auto& func = *it;
if (func->getFunctionName() == stdstrFunctionName)
return true;
}
return false;
}
我的问题是这两者几乎在做同样的事情,两者之间有什么区别吗。
或者只是同一事物的不同口味。
最佳答案
基本相同,但有一些不同:
- 在第二个片段
func != this->Functions.end()
中,Functions.end()
在每个循环中被调用(可能由编译器优化为-if 规则,但需要证明它是相同的)。 - 根据使用的标准(在 C++17 之前或之后),
Functions.end()
的类型应该等于Functions.end()
中的类型在 for-range 变体中。所以在 C++17 之前,sentinel end 不能使用 for range,可以使用旧的 for 循环。
关于c++ - 每个循环的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753358/