What STL function can I use to replace "while (var != nullptr)" loop?

Viewed 123

In book C++ Core Guidelines Explained: Best Practices for Modern C++ there is a quote:

There is a proverb in modern C++: “When you use explicit loops, you don’t know the algorithms of the STL.”

I am writing a program at the moment, which uses an explicit for loop, that changes an object pointed to by a variable in each iteration, until it points to nullptr.

    for(auto object = get_object(arg);object != nullptr;object = get_object_next(arg)) {
       if (condition) {
         vector_of_objects.push_back(object);
       }
    }

What STL function would be better suited for this than an explicit for loop?

1 Answers

Algorithms are ultimately built on iterators. Your loop is not. Therefore, there is no algorithm to fit it.

Now, if you're using this particular get_object/get_object_next interface frequently, it might be worthwhile to develop an iterator/range version of it. Presumably this would be some form of InputIterator/Range. The iterator would store the arg and a current object. ++ would replace the current object with get_object_next(arg). It's a pretty simple interface, and the C++20 concepts system makes writing conforming iterators easier than ever (at the very least, it's easy to check to see if it is a valid std::input_iterator).

But if you only have a couple of places that use these loops, it's probably not worthwhile.

Of course, "couple of places" and "used frequently" are states that can change over time. So it may be worthwhile to provide a range/iterator interface if you think it might be frequently used.

Related