【问题标题】:How to push a value inside a vector which in a c++ pair?如何将值推送到 C++ 对中的向量中?
【发布时间】:2020-08-11 20:25:59
【问题描述】:

我遇到了一种情况,我无法找到一种方法来推送vector 中的值,而pair 中的值。我已经创建了pair<int, vector<string>>priority_queue,我想在vector 中推送值,例如:

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

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

【问题讨论】:

  • 您到底想达到什么目标?在包含 pushed 或 emplaced in pq 的对之后修改 vector&lt;string&gt; 的内容?
  • pq.push({1, {"hello", "world"}});

标签: c++ c++14 priority-queue std-pair


【解决方案1】:

您无权访问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

【讨论】:

  • 请不要向有多个operator[]的新手开发者推荐相同的agrument的代码。 std::map::operator[] 是相当昂贵的操作。
  • @Slava 那么您希望如何多次访问给定键的元素?你在想auto &amp;elem = m[1]; elem = {"I", "a"}; elem.push_back(...); 之类的东西吗?像这样使用operator[] 没有任何问题。如果您想提高效率,请改用std::unordered_map
  • 仍然错过了OP没有澄清的点,他需要什么,你在建议一些数据结构。另外,添加到@Slava 说,对于新手演示的using namespace std; 的建议也不是一个好主意。
  • 是的,类似的。而且我可能出于不同的原因需要std::map,我认为这不是在您的代码中添加不必要的低效率的好借口。尤其是首先使用operator[] 也不是很有效。
【解决方案2】:

非常感谢您的澄清。我能够解决这个问题,这就是我的解决方法。

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

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2017-11-07
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多