问题
include <queue>
using namespace std;
char msg[1000];
Now, I want to have a queue that can store 5 of this kind of msg. So, it is a queue of size 5 that contains 5 arrays of characters, each array can contain up to 1000 chars.
How can I initiate the queue? I tried this but it did not work.
char msg[1000];
queue<msg> p;
回答1:
Edit: std::vector may be better choice, just reread you question and saw the size of the character array. If you are using it to store binary data, a std::queue< std::vector <char> > msgs is probably your best choice.
You cannot use a variable as a type. You could have a queue of character pointers though.
#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;
}
You could also just use std::string and avoid mistakes. If you use a char* you want a function to add msgs to queue, they cannot be on the stack (ie you would need to create them with new or malloc) than you would have to remember to delete them when you processed the queue. There would be no easy way to determine if one is in global space, one is on the stack, or one was made with new. Would lead to undefined behavior or memory leaks when not handled correct. std::string would avoid all of these problems.
#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;
}
If it is just 5 Standard messages, then const char* would be a decent choice, but if they are always the same messages, you should consider a queue of integers that refer to the message you want. This way you could associate more actions with it. But than you could also consider a queue of objects.
#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;
}
回答2:
struct msg {
char data[1000];
};
queue<msg> p;
回答3:
msg is an array, not a type. And since arrays are not copyable, this is not going to work anyway. Why not a std::queue<std::string> instead?
回答4:
First of all, you need a '#' sign in front of your include statement.
Secondly, when you declare queue, you put the type you want it to contain in the angle brackets (in your case 'char*'), not a variable name like 'msg'.
来源:https://stackoverflow.com/questions/8408776/queue-of-array-of-characters