从 STL 优先级队列 C++ (QtCreator) 打印结构
Print structure from STL priority queue C++ (QtCreator)
我无法从优先队列打印数据。这个数据是结构。如何打印队列中的结构?
这是我的结构:
struct pinfo
{
int p_id;
char path[50];
int type;
int priority;
};
这里我尝试打印我的数据:
void showpq(priority_queue <pinfo> pQueue)
{
priority_queue <pinfo> g = pQueue;
while (!g.empty())
{
cout << "\t" << g.top();
g.pop();
}
cout << '\n';
}
当我尝试打印数据时收到错误消息:
main.cpp:23: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const value_type {aka const pinfo}’)
cout << "\t" << g.top();
这与存储在 priority_queue
中的数据无关。您还没有告诉程序如何打印您的 pinfo
类型。你需要为它创建一个 operator<<
,像这样:
std::ostream& operator<< (std::ostream& os, pinfo const& p)
{
os << p.p_id << ", " << p.path << ", " << p.type << ", " << p.priority;
// or however you want the members to be formatted
return os; // make sure you return the stream so you can chain output operations
}
您需要定义一个具有以下签名的函数:
std::ostream& operator<<(std::ostream&&, const pinfo&);
当您将 g.top()
管道化到 std::cout
时,编译器会知道这一点。中缀 <<
运算符只是调用此函数(或左侧对象的 operator<<
方法)。只有少数简单的标准类型在标准库中预定义了 operator<<
- 其余的需要自定义定义。
我无法从优先队列打印数据。这个数据是结构。如何打印队列中的结构?
这是我的结构:
struct pinfo
{
int p_id;
char path[50];
int type;
int priority;
};
这里我尝试打印我的数据:
void showpq(priority_queue <pinfo> pQueue)
{
priority_queue <pinfo> g = pQueue;
while (!g.empty())
{
cout << "\t" << g.top();
g.pop();
}
cout << '\n';
}
当我尝试打印数据时收到错误消息:
main.cpp:23: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const value_type {aka const pinfo}’)
cout << "\t" << g.top();
这与存储在 priority_queue
中的数据无关。您还没有告诉程序如何打印您的 pinfo
类型。你需要为它创建一个 operator<<
,像这样:
std::ostream& operator<< (std::ostream& os, pinfo const& p)
{
os << p.p_id << ", " << p.path << ", " << p.type << ", " << p.priority;
// or however you want the members to be formatted
return os; // make sure you return the stream so you can chain output operations
}
您需要定义一个具有以下签名的函数:
std::ostream& operator<<(std::ostream&&, const pinfo&);
当您将 g.top()
管道化到 std::cout
时,编译器会知道这一点。中缀 <<
运算符只是调用此函数(或左侧对象的 operator<<
方法)。只有少数简单的标准类型在标准库中预定义了 operator<<
- 其余的需要自定义定义。