简体   繁体   中英

What's wrong with this C++ List?

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 use list.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 random being one since it will always be 1 or 0. In other words, the if bit will execute if it's 0, and the else bit will execute otherwise (when it's 1).

Fixing all that gives you:

#include <iostream>
#include <list>
#include <limits>
#include <cstdlib>

int main (void) {
    int random;
    std::list<int> MyList;

    for (int i = 10; i > 0; i--) {
        random = rand() % 2;
        if (random == 0) {
            if (MyList.empty()) {
                for (int k = 10; k > 0; k--) {
                    MyList.push_front (k);
                }
            }
        } else {
            if (!MyList.empty()) {
                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;
}

Obviously, this line is not correct:

if(MyList.front() == NULL){

Since MyList.front() is the reference of "int" type.

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