1

I have a class Priority Queue with method push() which takes two args: value and priority.

#include <vector>
#include <iostream>

class PriorityQueue
{
private:
    std::vector<std::pair<int, int>> _queue;

public:
    int top();
    int pop();
    void push(int, int);
    int size();
    PriorityQueue();
    PriorityQueue(int, int);
    friend std::ostream& operator<<(std::ostream&, PriorityQueue&);
};

How can I overload [] operator for it to work like this:

queue[priority]=value;

should mean

queue.push(priority, value);

?

depruss1an
  • 13
  • 2
  • 5
    Have `operator[] ` return a new object that in turn overrides `operator=` to actually calls `push` – Botje Nov 20 '20 at 08:06
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – TruthSeeker Nov 20 '20 at 08:07
  • 1
    The missing part here is what do you expect `value = queue[priority];` to do. – john Nov 20 '20 at 08:13

2 Answers2

3

You have to return type which will do the push on operator=, something like:

class PriorityQueue
{
private:
    std::vector<std::pair<int, int>> _queue;

    struct Proxy
    {
        PriorityQueue* queue;
        int priority;

        Proxy& operator=(int value) { queue->push(priority, value); return *this; }
    };

public:
    // ...
    Proxy operator[](int priority) { return {this, priority}; }
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

How can I overload [] operator in C++ for a function of two args?

The subscript operator is always a binary operator i.e. it always has two operands. If you define the subscript as a member operator, then the left hand operand will be *this and as such you can only have one more operand.

How can I overload [] operator for it to work like this:

queue[priority]=value;

In the subscript operator overload, return an object that points to *this and has an overloaded assignment operator that calls queue.push(priority, value).

eerorika
  • 232,697
  • 12
  • 197
  • 326