0

Hello every body

I'm trying to iterate through a list for a certian number of times using a for loop.
below is the current code I've written, but this will iterate through the list until it ends.

list<FileInfo*>::iterator  p = currentlist.begin();
  while(p != currentlist.end()) {

    cout << (*p)->remainingtime << " ";
    (*p)->remainingtime--;
    cout << (*p)->remainingtime << " ";


if ((*p)->remainingtime==0){
    p = currentlist.erase(p);
}
}    
cout << "\n\n";

Edited by Ahmed2: n/a

3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by Schol-R-LEA
0

How many times do you want it to loop?
You can set up a counter to break after that many times...

#include <iostream>
#include <list>
using namespace std;

int main(void)
{
   list<string> lst_str;
   lst_str.push_back("once");
   lst_str.push_back("upon");
   lst_str.push_back("a");
   lst_str.push_back("time");
   lst_str.push_back("there");
   lst_str.push_back("were");
   lst_str.push_back("three");
   lst_str.push_back("bears");
   //
   list<string>::iterator it = lst_str.begin();

   for(int i=0 ;i<4; i++)
   {
      cout << (*it++).c_str() << endl;
   }

   return 0;
}

Edited by thines01: added code

0

Assuming I'm understanding this correctly, what you need to do is combine a regular for() loop conditional with the test for the end of the loop as you have it above:

for (int i = 0; (i < iterations) && (p != currentlist.end()); i++)
{
  // code goes here
}

The reason you need both is for the case where the list is shorter than the number of iterations.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.