How can I get out of the loop and continue the loop again?

Examples of two approaches, assuming that it’s the index you’re interested in.

Calling a function when an element is found:

void search(const std::vector<int>& v, int x, std::function<void(int)> index_handler)
{
    for (int i = 0; i < v.size(); ++i)
    {
        if (v[i] == x)
        {
            index_handler(i);
        }
    }
}

Letting the caller determine the starting point (like std::string::find):

int search_2(const std::vector<int>& v, int x, int start)
{
    for (int i = start; i < v.size(); ++i)
    {
        if (v[i] == x)
        {
            return i;
        }
    }
    return -1;
}

Example use:

int main()
{
    // Method 1
    std::vector<int> vs = { 1, 2, 1, 2, 1, 2, 3};
    search(vs, 2, [](int i) { std::cout << "found at index " << i << '\n'; });

    // Method 2
    int index = search_2(vs, 2, 0);
    while (index >= 0)
    {
        std::cout << "found at index " << index << '\n';
        index = search_2(vs, 2, index + 1);
    }
}

The second method is more flexible, but also messier and more error-prone.

Leave a Comment