Search code examples
c++c++14priority-queuestd-pair

How to push a value inside a vector which in a c++ pair?


I have come across a scenario where I am not able to find a way to push a value in the vector which is in the pair. I have made a priority_queue of pair<int, vector<string>> and I want to push values in the vector, for example:

priority_queue<pair<int, vector<string>> pq;

I want to know how to push elements in this priority queue.


Solution

  • You don't have access to the underlying container of a std::priority_queue, so you can't access any of the std::vector elements you store in it, other than the top() element, eg:

    priority_queue<pair<int, vector<string>> pq;
    pq.push(...);
    pq.emplace(...);
    ...
    // use pq.top().second as needed...
    

    You can iterate the strings in the vector in the pair returned by top(), but you can't push_back() more string into the vector since the pair will be const, and thus the vector will also be const.

    std::priority_queue is probably not the best container for you to use. Maybe a std::map would make more sense?

    map<int, vector<string>> m;
    m[1] = vector<string>{"I", "a"};
    m[1].push_back(...);
    

    Live Demo