在队列中推送结构变量
pushing structure variable in queue
#include <iostream>
#include <queue>
using namespace std;
int main () {
struct process {
int burst;
int ar;
};
int x=4;
process a[x];
queue <string> names; /* Declare a queue */
names.push(a[1]);
return 0;
}
我正在尝试将结构变量推送到队列中,但它没有接受它并给出错误
no matching function for #include queue and invalid argument
我该怎么做?
C++ 是一种强类型语言。在行 names.push(a[1]);
中,您试图将 struct
(从您的 process a[x];
数组)推入 queue<string>
。您的结构不是 string
,因此编译器将发出错误。你至少需要一个queue<process>
.
其他问题:可变长度数组不是标准的 C++ (process a[x];
)。请改用 std::vector<process>
。这是一些有效的简单示例:
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int main () {
struct process // move this outside of main() if you don't compile with C++11 support
{
int burst;
int ar;
};
vector<process> a;
// insert two processes
a.push_back({21, 42});
a.push_back({10, 20});
queue <process> names; /* Declare a queue */
names.push(a[1]); // now we can push the second element, same type
return 0; // no need for this, really
}
编辑
用于实例化模板的本地定义 classes/structs 仅在 C++11 及更高版本中有效,参见例如Why can I define structures and classes within a function in C++? 以及其中的答案。如果您无权访问符合 C++11 的编译器,请将 struct
定义移到 main()
.
之外
#include <iostream>
#include <queue>
using namespace std;
int main () {
struct process {
int burst;
int ar;
};
int x=4;
process a[x];
queue <string> names; /* Declare a queue */
names.push(a[1]);
return 0;
}
我正在尝试将结构变量推送到队列中,但它没有接受它并给出错误
no matching function for #include queue and invalid argument
我该怎么做?
C++ 是一种强类型语言。在行 names.push(a[1]);
中,您试图将 struct
(从您的 process a[x];
数组)推入 queue<string>
。您的结构不是 string
,因此编译器将发出错误。你至少需要一个queue<process>
.
其他问题:可变长度数组不是标准的 C++ (process a[x];
)。请改用 std::vector<process>
。这是一些有效的简单示例:
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int main () {
struct process // move this outside of main() if you don't compile with C++11 support
{
int burst;
int ar;
};
vector<process> a;
// insert two processes
a.push_back({21, 42});
a.push_back({10, 20});
queue <process> names; /* Declare a queue */
names.push(a[1]); // now we can push the second element, same type
return 0; // no need for this, really
}
编辑
用于实例化模板的本地定义 classes/structs 仅在 C++11 及更高版本中有效,参见例如Why can I define structures and classes within a function in C++? 以及其中的答案。如果您无权访问符合 C++11 的编译器,请将 struct
定义移到 main()
.