Search code examples
c++vectoriterator

Start iterating vector from the nth element


I'm trying to iterate a vector from the nth element onwards. Not sure how should i go about doing this.

I have a vector A and B. My vector A has 10 elements of PC1-PC10 and my vector B has 20 elements of User1-User20.
So what I want to do is that when both my vector A and B reaches the 10th element, meaning to say the last element for vector A, I want to repeat iterating vector A but start iterating vector B from the 11th element so that I can do some stuff with it.

Below is the simplified code that I came up with but technically its about the same thing:

vector<string>::iterator b = vecB.begin();
for (int i = 1; i < 2; i++) {
    for (vector<string>::iterator a = vecA.begin(); a != vecA.end() ; a++) {
        if (a == vecA.end()) {
            b = vecB.begin() + 10; //here the iterator for verB should start from the 11th element
        }
    ++b
    }
}

Should I mess with the iterator for vector B? Or is there another alternative?

EDIT
It seems that I have been asking the wrong question after all. I have marked the answer to this question and will be posting another shortly. Thanks for the quick response to my question!


Solution

  • The if condition inside the nested loop will never be true, because it conflicts with the loop condition:

    for (vector<string>::iterator a = vecA.begin(); a != vecA.end() ; a++) {
    // This check ----------------------------------^^^^^^^^^^^^^^^
    // guarantees that this will never succeed:
    //      vvvvvvvvvvvvvvv
        if (a == vecA.end()) {
            ...
        }
    }
    

    You should rewrite the code like this:

    vector<string>::iterator b = vecB.begin();
    // Check that vecB has sufficient number of elements before entering the loop.
    for (int i = 1 ; i < 2 ; i++) {
        for (vector<string>::iterator a = vecA.begin(); a != vecA.end() ; ++a, ++b) {
            ...
        }
        // At this point we know for sure that a == vecA.end(),
        // because it is a post-condition of the for loop above.
        b = std::next(vecB.begin(), 11);
    }
    

    The call of ++b can be moved into the loop header.

    Note the use of std::next: although

    b = vecB.begin() + 10;
    

    compiles for vectors, it is not guaranteed for all kinds of containers. Use std::next instead:

    b = std::next(vecB.begin(), 11);
    

    Note: This code makes an assumption that vecB has at least 11 elements more than vecA does. This may be OK if you check that assumption before entering the loop. If this assumption is broken, the code would have undefined behavior.