这个C++列表有什么问题?
What's wrong with this C++ List?
我有一个基本的工作,只需生成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"类型的引用。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- c++无值sort()的问题是什么?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 什么是钻石问题?是一系列问题还是特定问题?
- 格式说明符C++有什么问题
- 我应该在 main 函数中写什么来测试我的问题?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 方法问题 - 什么会改变值,什么不会改变?什么是无效的?