如何将值推入C ++对中的向量中?

问题描述

我遇到一种情况,我无法找到一种方法来推送vector中的pair中的值。我制作了priority_queue的{​​{1}},并且想在pair<int,vector<string>>中推送值,例如:

vector

我想知道如何在此优先级队列中推送元素。

解决方法

您无权访问std::priority_queue的基础容器,因此您无法访问其中存储的std::vector元素之外的任何top()元素,例如:

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

您可以将vector返回的pair中的top()中的字符串进行迭代,但是由于{ push_back()将是vector,因此pair也将是const

vector可能不是您要使用的最佳容器。也许const会更有意义?

std::priority_queue

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...