简体   繁体   中英

c++ iterating through whole list

I have function that takes in a list for example {10,14,2,4,8} I then iterate through the whole list and as i am going I divide it by a divisor and then % 2. The loop should keep on running until the divisor is larger then the largest number in the list. A sample output would be;

10=0
14=0
2=0
4=0
8=0

and then divisor get multiplied by 2 and produces.

10=1
14=1
...

I am only getting the first part and then it stops. I know my logic is wrong some where.

void Splice(std::list<int> list_Original)
{
   int largest_number_in_list=getMax(list_Original);
   int divisor=1;
   std::list<int> new_list;

   for(std::list<int>::iterator i=list_Original.begin();i !=      list_Original.end();i++)
   {
       if(divisor<largest_number_in_list)
       {
           int n=((*i/divisor)%2);
           std::cout<<*i<<"="<<n<<std::endl;
           //new_list.push_back(n);
           divisor=2*divisor;
           //std::cout<<"hihh";
        }

        for(std::list<int>::iterator i=new_list.begin();i!=new_list.end();i++)
        {
            std::cout<<*i<<std::endl;
        }
    }
}

Ignoring whatever you're doing with the "new list", you're for loop is exiting after it iterates over the list once. You're also doubling the divisor during every iteration. You want the check between divisor and the largest number to loop around the for loop so use a while .

while (divisor < largest_number_in_list)
{   
    for(std::list<int>::iterator i=list_Original.begin();i !=list_Original.end();i++)
    {
        int n=((*i/divisor)%2);
        std::cout<<*i<<"="<<n<<std::endl;
    }

    divisor=2*divisor;
}

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