这个C++列表有什么问题?

What's wrong with this C++ List?

本文关键字:问题 什么 C++ 列表 这个      更新时间:2023-10-16

我有一个基本的工作,只需生成10个状态的随机序列,0=生产,1=消费。对于每个0,我需要填写列表,如果列表已满,则不采取任何措施;对于1,清空列表。。。如果它已经空了,什么也不做。

我做了简单的pop_front,push_front把东西放进和放出列表。。。但我真的不知道为什么这是错误的。。。有什么想法吗?

#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()返回对第一个元素的引用,我认为您希望使用list.empty()来检测空或满的状态(在您的特定情况下,您是其中之一,没有灰色区域)。

此外,在某些圈子里,"使用命名空间std"是不受欢迎的,而且你还没有包括numeric_limits的头文件(尽管如果你只是在IDE中使用它作为"按任意键继续"方法,这可能是不必要的)。

此外,不需要检查random是否为1,因为它将始终为1或0。换句话说,如果if位为0,则执行该位,否则(当else位为1时)执行该位。

修复所有给你的:

#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;
}

显然,这一行不正确:

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

由于MyList.front()是"int"类型的引用。