gpt4 book ai didi

c++ - 插入 STL 集中

转载 作者:行者123 更新时间:2023-11-30 04:05:34 29 4
gpt4 key购买 nike

我需要在 priority_queue 中保存一个整数集合。但是我需要能够删除这些整数中的一个,即使它不是我容器的第一个元素。我无法使用 std::priority_queue。我选择使用一个集合来根据自定义比较器对整数进行排序。

class Comparator
{
vector<double>& cmp;
public:
Comparator(vector<double>& a_cmp) : cmp(a_cmp) {}
bool operator() (int i, int j) const {return cmp.at(i) < cmp.at(j);}
};

然后我像这样使用了这个集合:

Comparator comp = Comparator(a_cmp);
set<int, Comparator> my_set (comp);
my_set.insert(index);

然而,对于两个整数 i 和 j,例如 i != j 和 cmp.at(i) == cmp.at(j),如果我尝试同时插入两个整数,则只会将一个插入到集合中.我知道这是 std::set 的行为,但是我更愿意将这两个整数(不等于)插入到彼此相邻的集合中。换句话说,我需要在对集合进行排序时使用我的自定义比较器,但不能阻止插入。我认为当我修改我的比较功能时它可能会起作用:

bool operator() (int i, int j) const {return cmp.at(i) =< cmp.at(j);}

但是我不确定它是否完全正确。我应该将 std::vector 与我的原始比较函数一起使用,然后用 std::sort 对其进行排序吗?感谢您的回答。

最佳答案

However it appears that for two integers i and j such as i != j and cmp.at(i) == cmp.at(j), if I try to insert both, only one would be inserted into the set. I understand that it is the behaviour of std::set, however I would have prefered if both those integers (which are not equals) would be inserted in the set next to each other.

在你的 operator() 中,你可以这样做

return (cmp.at(i) < cmp.at(j)) || (!(cmp.at(j) < cmp.at(i)) && (i < j));

这基本上是说集合将按索引处的值升序排序,然后按索引本身的相对值排序。

关于c++ - 插入 STL 集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23239192/

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