Continue loop(for) at position break(Vector C++)

I have a code:

uint8_t x = 0;
typedef std::vector<Data> Data_Record;
const Data_Record& getData() const;
main()
{
    while(1)
    {
        get1();
        get2();
    }
}
void get1()
{
    for (const auto& dataRecord : file.getData())
    {
        if( x==10)
        {
           break;
        }
        x++;
    }
}

You see dataRecord read at position 10. How to continue get1() with next dataRecord (postion 11). Please help me. Thank you so much!

  • You have to rewrite your code, coroutine or handle that yourself (with a class?).

    – 




  • 1

    Use and old-style for loop with an iterator. Remember the iterator when breaking, and then use it as a starting point of the next loop.

    – 

  • 1

    What should happens when all elements have been processed? restart, end the main loop?

    – 

  • @Jarod42 it is only send data and continue to read data

    – 

  • You cannot do it in the get1(). You have to make changes in getData() or better to write an overload of getData() which returns from where it left last.

    – 

Instead of using a while loop, you can try using a for loop.

uint8_t x = 0;
size_t currentPosition = 0;

void get1()
{
    const auto& data = file.getData();
    
    for (size_t i = currentPosition; i < data.size(); ++i)
    {
        const auto& dataRecord = data[i];
        
        if (x == 10)
        {
            x = 0;
            currentPosition = i + 1;
            return;
        }
        
        x++;
    }
}

Leave a Comment