Coding

C++ std::next

Another way to increment an iterator, and preferred if you’re using std::move in your code, is to use std::next over ++.

Here’s an example:

#include <iostream>

int main(int, char**)
{
    // Our string to iterate over
    std::string message = "Hello world!";

    auto itr = message.begin();
    while (itr != message.end())
    {
        std::cout << "char: " << (*itr) << "\n";

        // Step up the iterator
        itr = std::next(itr);
    }

    std::cout << "All done!\n";
}

Now, since we are not modifying anything in our string, we could also use const iterators, simply replacing begin and end with cbegin and cend :

int main(int, char**)
{
    // Our string to iterate over
    std::string message = "Hello world!";

    auto itr = message.cbegin();
    while (itr != message.cend())
    {
        std::cout << "char: " << (*itr) << "\n";

        // Step up the iterator
        itr = std::next(itr);
    }

    std::cout << "All done!\n";
}

Languages:
C++11, C++17

Refs:
https://en.cppreference.com/w/cpp/iterator/next
https://en.cppreference.com/w/cpp/iterator/begin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.