【问题标题】:C++ How to access elements in a vector of queues of an objectC ++如何访问对象队列向量中的元素
【发布时间】:2016-03-09 18:30:29
【问题描述】:

所以我有一个类叫PCB:

class PCB
{
    private:

        int PID;
        string filename;
        int memStart;
        string cdrw;
        int filelength;

    public:

        PCB();
        PCB(int, string, int, string, int);
        virtual ~PCB();
        void getParam();
};

我有一个队列向量:vector<queue<PCB>> printer;

如何访问向量中第一个队列的第一个元素?我将如何使用我的类函数?它看起来像printer[0].getParam 吗?

【问题讨论】:

    标签: c++ class vector queue


    【解决方案1】:

    printer[0] 让您可以访问第一个queue<PCB>

    printer[0].front() 让您可以访问位于第一个queue<PCB> 队列前面的PCB

    printer[0].front().getParam() 允许您在第一个queue<PCB> 的队列前面的PCB 上调用getParam() 函数。

    【讨论】:

    • 谢谢,我在想这个,但我不太确定如何编写它的语法。
    • @TheCoxer,没问题。很高兴能提供帮助。
    【解决方案2】:

    std::queue 仅提供使用front()back() 直接访问第一个和最后一个项目的设施。因此,如果您想从向量中调用其中一项的函数,那么您将使用

    std::vector<std::queue<PCB>> printer;
    // fill printer
    printer[0].front().getParam();
    // or
    printer[0].back().getParam();
    

    总之

    printer[some_index].front()
    // or
    printer[some_index].back()
    

    返回对容器中该索引处的PCB 的引用。

    【讨论】:

    • 如果我想在同一个对象上调用两个方法怎么办?
    • @bdbasinger 然后你会使用printer[some_index].front().func1; 然后printer[some_index].front().func2;
    • 再次使用 .front() 不会导致它在第一次使用后移动到队列中的下一个项目?
    • @bdbasinger front 只为您提供对第一个元素的引用。它不会删除任何东西。要删除,您需要使用 pop。
    【解决方案3】:

    这是一个使用您的代码的简单示例;

    int main()
    {
        vector<queue<PCB>> printer;
    
        // Create object your PCB class.
        PCB pcbObject;
    
        // Declare a queue
        queue<PCB> que;
    
        // Add the PCB class object to queue
        que.push(pcbObject);
    
        // Push the queue to vector.
        printer.push_back(que);
    
        //Get the first value
        printer[0].front().getParam();
    
        // Remove the element PCB
        printer[0].pop();
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-06
      • 2021-12-28
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多