简体   繁体   中英

Decrementing an iterator until the .begin() of a vector

I need to read a vector backward from a certain position of an iterator, and put up to n1 values in the dictionnary array.

I though about making a loop and decrementing the iterator, but for some reasons I'm stuck in an infinite loop.

I think there's an issue in the while condition?

//I read all the vSignal vector
while (vSignalIt != vSignal.end()) {

    i = 0;
    vSignalIt2 = vSignalIt;

    //Filling the dictionnary array
    if (vSignalIt != vSignal.begin()) {
        do 
        {
            dictionnary[i] = *vSignalIt2;
            vSignalIt2--;
            i++;
        } while (vSignalIt2 != vSignal.begin() || i < (uint8_t)n1);
    }

    //Do something with the value of dictionnary and increase vSignalIt to advance forward in the vSignal vector

}

change the '||' to '&&'

You are using the wrong conditional checker for your statement. Currently it is:

while (vSignalIt2 != vSignal.begin() || i < (uint8_t)n1);

But it should be:

while (vSignalIt2 != vSignal.begin() && i < (uint8_t)n1); //<-- && means 'and'

Also, as a recommendation, you should probably use a reverse_iterator because it is built for the purpose.

You might want to consider standard algorithms instead:

auto vSignalIt = vSignal.rbegin(); // or some other reverse iterator
auto n = std::min(n1, std::distance(vSignalIt, vSignal.rend());
std::copy_n(vSignalIt, n, std::back_inserter(dictionary));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM