c++ - 每个循环的区别

标签 c++ c++11 c++14

我正在尝试使用 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/

相关文章:

c++ - 不完整类型无效应用 'Test::Impl'

具有默认模板参数的 C++14 变量模板?

c++ - 使用 MoveWindow 或 SetWindowPos 时,编辑控件/组合框的窗口大小未正确调整

c++ - 省略数据成员对象的初始化列表条目

c++ - 使用 C++ 11 在二叉树(或任意树)上实现迭代器

c++ - 使用 make_shared<std::thread> 创建 shared_ptr<std::thread> 的实例

c++ - 按值传递函数(?)而不是函数指针?

c++ - 如果 atomic_flag 变量是类的成员,我该如何初始化它?

c++11 - std::move-如何警告程序员不要使用* move 自*对象

c++ - 打开外部应用程序并关闭当前应用程序