2

So I have a loop that goes something like

for (r = 0; r < k; r++) {
    pair p = {r, D[r]};
    queue.push(p);
}

where pair is defined as

struct pair {
    int u;
    float d;
}

Is this a legal way to create k pairs and push them onto a priority queue? Do the pairs still exist on the queue in their original form even though p gets overwritten each time? Or does each pair that's already on the queue get automatically updated to the new value of p, resulting in a queue full of identical copies of the same pair?

Thanks!

2 Answers 2

4

The code is fine.

p gets copied into the queue; it doesn't matter what happens to the original after the copy is made.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, your code works as is. The default copy constructor of p is called, and a copy is pushed into queue. However, you can simplify your code a bit by adding a constructor. If you define pair as:

struct pair {
    pair(int u_, float d_) : u(u_), d(d_){}
    int u;
    float d;
};

Then in your loop, you can simply do:

for (r = 0; r < k; r++) {
    queue.push_back(pair(r, D[r]));
}

That way, it is a bit more clear that you are intentionally pushing a copy. Also, make sure you have a ; after the end of your struct declaration! If you forget, you can end up with some mysterious compiler errors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.