TheCoxer
TheCoxer

Reputation: 511

C++ How to access elements in a vector of queues of an object

So I have a class called 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();
};

And I have a vector of queues: vector<queue<PCB>> printer;

How would I access the first element of the first queue in the vector? How would I use my class functions? Would it look like printer[0].getParam?

Upvotes: 0

Views: 1674

Answers (3)

NathanOliver
NathanOliver

Reputation: 180424

A std::queue only provides facilities to access the first and last items directly using front() or back(). So if you want to call a function on one of those items from the vector then you would use

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

In short

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

Returns a reference to the PCB in the container at that index.

Upvotes: 1

Sudipta Kumar Sahoo
Sudipta Kumar Sahoo

Reputation: 1147

Here is a simple example using your code;

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;
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

printer[0] gives you access to the first queue<PCB>.

printer[0].front() gives you access to the PCB at the front of the queue of the first queue<PCB>.

printer[0].front().getParam() allows you to call the getParam() function on the the PCB at the front of the queue of the first queue<PCB>.

Upvotes: 2

Related Questions