include <queue>
using namespace std;
char msg[1000];
现在,我想拥有一个队列,可以存储5种这类味精。所以,它是一个包含5个字符数组的5号队列,每个数组最多可以包含1000个字符。排列字符的队列
如何启动队列?我试过这个,但没有奏效。
char msg[1000];
queue<msg> p;
include <queue>
using namespace std;
char msg[1000];
现在,我想拥有一个队列,可以存储5种这类味精。所以,它是一个包含5个字符数组的5号队列,每个数组最多可以包含1000个字符。排列字符的队列
如何启动队列?我试过这个,但没有奏效。
char msg[1000];
queue<msg> p;
编辑:std :: vector可能是更好的选择,只是重读你的问题,看到字符数组的大小。如果您正在使用它来存储二进制数据,则std::queue< std::vector <char> > msgs
可能是您的最佳选择。
您不能使用变量作为类型。尽管你可以有一个字符指针队列。
#include <iostream>
#include <queue>
std::queue <char*> msgs;
int main()
{
char one[50]="Hello";
msgs.push(one);
char two[50]="World\n\n";
msgs.push(two);
msgs.push("This works two even though it is a const character array, you should not modify it when you pop it though.");
while(!msgs.empty())
{
std::cout << msgs.front();
msgs.pop();
}
return 1;
}
你也可以使用std :: string并避免错误。如果你使用的是char*
,你需要一个函数来向队列中添加信息,它们不能在堆栈上(即你需要用new
或malloc
创建它们),比你在处理队列时必须记得删除它们。要确定一个人是在全球空间,一个是在堆栈中,还是一个是在新的空间中,将没有简单的方法。未处理正确时会导致未定义的行为或内存泄漏。 std::string
可以避免所有这些问题。
#include <iostream>
#include <queue>
#include <string>
std::queue <std::string> msgs;
int main()
{
msgs.push("Hello");
msgs.push("World");
while(!msgs.empty())
{
std::cout << msgs.front();
msgs.pop();
}
return 1;
}
如果只是5标准的消息,然后const char*
将是一个不错的选择,但如果他们总是相同的邮件,你应该考虑引用到你想要的消息整数的队列。这样你可以将更多的操作与它联系起来。但是,你也可以考虑一个对象队列。
#include <iostream>
#include <queue>
std::queue <int> msgs;
int main()
{
msgs.push(1);
msgs.push(2);
while(!msgs.empty())
{
switch(msgs.front())
{
case 1:
std::cout << "Hello";
break;
case 2:
std::cout << "World";
break;
default:
std::cout << "Unkown Message";
}
msgs.pop();
}
return 1;
}
非常感谢!它的工作原理 –
谢谢。我做了'deque
我不知道什么newString()是,但我认为消息应该只是我在这种情况下的字符* ...你可以发布什么newString做你的问题? –
struct msg {
char data[1000];
};
queue<msg> p;
msg
是一个数组,而不是一个类型。由于数组不可复制,所以这不会起作用。为什么不是std::queue<std::string>
呢?
感谢您的建议,但我不得不使用char *这次 –
@JJLiu:为什么?这很愚蠢。 –
首先,你需要在你的include语句前加'#'符号。其次,当你声明队列时,你把你想要它包含的类型放在尖括号中(在你的情况下是'char *'),而不是像'msg'这样的变量名。
+1反击匿名downvoter。据我所知,这个答案没有错。 –
谢谢,答案很好 –
@AlfP。Steinbach:我基本上同意,除了“取消”别人的投票权不是你的工作。这真的是一个值得赞赏的“伟大”答案吗? –
什么不起作用?编译器错误? –
'std :: string'是整洁的。 – AusCBloke
@JoeMcGrath谢谢。我做了'deque QUEUE; while(1){char msg [1000]; msg = newString(); QUEUE.push(MSG); }'。然后我发现队列中的所有元素都是相同的,因为它们引用了同样的东西'msg'。我该如何解决这个问题? –