首页 > 解决方案 > 嵌套容器:为什么我不能访问堆栈队列顶部的堆栈?C++

问题描述

所以我使用 STL 创建了一个堆栈队列,如下所示:

void main()
{
    queue<stack<string>> qos;
    stack<string> words;
    words.push("hey");
    qos.push(wors);
    cout<< (qos.pop()).top()<<endl;
}

预期行为:

返回单词

实际结果:

错误:成员引用基类型“void”不是结构或联合

我的问题是为什么它不返回我所期望的,我的意思是因为 qos.pop() 返回堆栈元素并且堆栈具有成员函数 top();

标签: c++stackcontainers

解决方案


你的变量wordsqos没有任何关系。

main()必须有一个返回类型int

您收到错误消息的原因是,可以调用queue<>::pop不返回值的错误消息。top()

你可能想要

#include <iostream>
#include <queue>
#include <stack>
#include <string>

int main()
{
    std::queue<std::stack<std::string>> qos;
    std::stack<std::string> words;

    words.push("hey");
    qos.push(words);

    std::cout << qos.front().top() << '\n';
}

推荐阅读