Search code examples
c++listwhile-loopiterator

Reverse while iteration not going backwards


I am trying to make a reverse loop through a list using while. I am trying the following code:

#include <iostream>
#include <list>


int main(){
    
    std::list <int> l1 = {1,2,3,4};
    
    auto it1 = l1.end();
    int val1;
    int sum1=0, exp1=1;
    
    int i = 0;
    while( it1 != l1.begin() ){
        --it1;
        val1 = *it1;
        
        sum1 +=  val1 * exp1;
        exp1 *= 10;
        i++ ;   
    }
    
    std::cout << sum1 << std::endl;
    
    return 0;
}

It is retuning 1234 while I was expecting the oposite: 4321

Why this? How do I make it work with while loop?


Solution

  • This statement:

    sum1 +=  val1 * exp1;
    

    produces the result 1234.

    That is in the first iteration of the while loop you get that sum1 is equal to 4. Then in the second iteration of the while loop you actually have according to the above statement:

    sum = 4 + 3 * 10;
    

    that result in 34 and so on.

    Instead you need to write

    sum = sum * exp1 + val1;.
    

    You could leave the statement:

    sum1 +=  val1 * exp1;
    

    as is if you would write the while loop like:

    auto it1 = l1.begin();
    //...
    while( it1 != l1.end() ){
    //...
    

    Another approach is to use the range-based for loop:

    for ( const auto &val1 : l1 )
    {
        sum1 += val1 * exp1;
        exp1 *= 10;
    }