I have a basic job, just generate a random sequence of 10 states, 0=produce, 1=consume. for every 0, I need to fill the list, if its full do nothing, and for a 1, empty the list… if its already empty, do nothing.
I did the simple pop_front, push_front to put things in and out of the list… but I don’t really know why this is wrong… any thoughts?
#include <iostream>
#include <list>
#include <cstdlib>
using namespace std;
int main(){
list<int> MyList;
int random;
for (int i=10; i>0; i--){
random = rand() % 2;
if(random == 0){
if(MyList.front() == NULL){
for(int k=10; k>0; k--){
MyList.push_front(k);
}
}
} else if(random == 1){
if(MyList.front() != NULL){
for(int j=10; j>0; j--){
MyList.pop_front();
}
}
}
std::cout << random << ", ";
}
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
list.front()returns a reference to the first element, I think you want to uselist.empty()to detect the state of being empty or full (in your particular case where you’re one or the other, with no grey areas).In addition, it’s frowned upon in certain circles to “use namespace std” and you haven’t included the header file for
numeric_limits(though it’s probably unnecessary if you’re just using that as a “Press any key to continue” method inside an IDE).Also there’s no need for the check of
randombeing one since it will always be 1 or 0. In other words, theifbit will execute if it’s 0, and theelsebit will execute otherwise (when it’s 1).Fixing all that gives you: