问题描述
我遇到一种情况,我无法找到一种方法来推送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
,
非常感谢您的澄清。我能够解决问题,这就是我的解决方法。
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);
}
};