gpt4 book ai didi

c++ - 在 C++11 中查找和访问优先级队列中的元素

转载 作者:太空狗 更新时间:2023-10-29 23:14:06 24 4
gpt4 key购买 nike

如何在 C++11 的优先级队列中找到一个元素并访问相应的元素?至于下面的例子:最好检查优先级队列 Q 中的元素是否存在并访问它。是否也可以编辑它?

意图:编写一个应用程序,我必须在其中检查特定对象是否已插入到优先级队列中。如果它被插入,那么我需要访问该特定对象并可能更新它。

#include <iostream>
#include <vector>
#include <string>
#include <queue>

struct Person {
int val;
std::string y;
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.val > rhs.val;
}
};

int main () {

std::vector<int> data = {5,4,3,2,1};
Person X1,X2,X3,X4,X5;
X1.val = 20;
X1.y = "twenty";

X2.val = 10;
X2.y = "ten";

X3.val = 50;
X3.y = "fifty";

X4.val = 5;
X4.y = "five";

X5.val = 0;
X5.y = "zero";

std::vector<Person> V;
V.push_back(X1);
V.push_back(X2);
V.push_back(X3);
V.push_back(X4);
V.push_back(X5);

std::priority_queue<Person,std::vector<Person>,Person> Q;

for (auto x: V) Q.push(x);
return 0;
}

最佳答案

对于这种用法,我建议您结合使用 std::priority_queue和一个 std::unordered_map .

让我们按如下方式重组您的数据:

struct PersonInfo {
std::string y;
};

这包含一个人的可变信息。

现在你有两个容器:

  • std::priority_queue<int>以前是 val 的值在你的Person类对象。

  • std::unordered_map<int, PersonInfo>将这些值映射到 PersonInfo

为了您陈述的意图

in which I have to check whether a particular object has been inserted into priority queue or not.

简单地检查是否使用 map 插入了东西;不过,请确保在推送和弹出优先级队列时更新它。

If it is being inserted, then I need to access that particular object and possibly update it.

只需使用无序映射即可。

关于c++ - 在 C++11 中查找和访问优先级队列中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com