0

I am trying to use for each loop in c++.

this->Functions is a vector.

std::vector< std::shared_ptr<Sum_Function> > Functions;

After reading i came across two different ways to do for each.

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

my question is that these both are nearly doing the same stuff , is there any difference between the two.

Or just different flavors for the same thing.

4
  • 1
    Another alternative: return std::any_of(Functions.begin(), Functions.end(), [&](const auto& f) { return f->getFunctionName() == stdstrFunctionName;} ); Commented Sep 2, 2019 at 8:04
  • @Jarod i know it was demo code , i have shown the function earlier. Commented Sep 2, 2019 at 8:07
  • i will edit it. Commented Sep 2, 2019 at 8:07
  • 1
    range-for might help you. Commented Sep 2, 2019 at 8:08

2 Answers 2

1

Mostly equivalent, but with some differences:

  • in second snippet func != this->Functions.end(), Functions.end() is called at each loop (might be optimized by compiler with as-if rule, but requires to proof that it is the same).
  • Depending of standard used (before C++17 or not), type of Functions.end() should be equal to the one from Functions.end() in the for-range variant. So prior to C++17, sentinel end cannot use for range and may use old for loop.
Sign up to request clarification or add additional context in comments.

Comments

1

It's mainly the same thing in two flavors. The range-based for loop expands to a loop based on iterators. But note that when the loop is critical for performance, this

for (auto func = this->Functions.begin(); func != this->Functions.end(); ++func)

is not ideal as the compiler might not be able to optimize the query for Functions.end() such that it is invoked only once. Recall that the termination condition in a manual for loop is evaluated every time, you might be better off with

for (auto func = this->Functions.begin(), end = this->Functions.end(); func != end; ++func)

As this necessarily introduces a second variable, it's definitely less readable than the range based for loop, so I'd advice you to use the range based for loop, or, as suggested in the comments, std::any_of from the <algorithm> header.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.