如何将值推送到 c++ 对中的向量中?

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

我遇到过这样一种情况,我无法找到将值推送到 pair 中的 vector 中的方法。我制作了 pair<int, vector<string>>priority_queue,我想在 vector 中推送值,例如:

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

我想知道如何压入这个优先级队列中的元素。

您无权访问 std::priority_queue 的底层容器,因此您无法访问存储在其中的任何 std::vector 元素,除了 top()元素,例如:

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

您可以在 top() 返回的 pair 中迭代 vector 中的字符串,但是您不能 push_back() 更多字符串进入 vector 因为 pair 将是 const,因此 vector 也将是 const

std::priority_queue 可能不是最适合您使用的容器。也许 std::map 更有意义?

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

Live Demo

非常感谢您的澄清。我能够解决问题,下面是我的处理方法。

typedef pair<int, vector<string>> pi;
class Compare {
    public:
    bool operator() (pair<int, vector<string>> a, pair<int, vector<string>> b) {
        return a.first > b.first;
    }  
};

class Solution {
public:
    
    string arrangeWords(string text) {
        int n = text.length();
        if(n==0)
            return "";
        text[0] = tolower(text[0]);
        unordered_map<int, vector<string>> m;
        string temp = "";
        for(int i = 0;i<n;i++) {
            if(text[i] != ' ') {
                temp += text[i];
            } else {
                m[temp.length()].push_back(temp);
                temp = "";
            }
            if(i==n-1) {
                m[temp.length()].push_back(temp);
            }
        }
        
        
        priority_queue<pi, vector<pi>, Compare> pq;
        for(auto x: m) {
            pq.push(make_pair(x.first, x.second));
        }
        
        string res = "";
        while(!pq.empty()) {
            auto t = pq.top(); pq.pop();
            int len = t.second.size();
            for(int i=0;i<len;i++) {
                res += t.second[i];
                res += " ";
            }
        }
        res[0] = toupper(res[0]);
        return res.substr(0, res.length()-1);
    }
};