gpt4 book ai didi

C++ STL 集 : Compare object with extrinsic state

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:30:12 31 4
gpt4 key购买 nike

这个定义在 OuterClass 中:

struct Compare
{
bool operator ()(const T&, const T&);
};
typedef set<T, Compare> MySet;

我的问题是比较函数 operator () 取决于 OuterClass 的状态。 (MySet 实例在优化算法期间使用,它们必须在不同阶段以不同方式排序。)

是否有任何方法/变通方法可以从比较函数 operator () 中访问 OuterClass 的非静态成员?

最佳答案

Is there any way/workaround to access nonstatic members of OuterClass from within the compare function operator ()?

有。只需为 Compare 编写一个用户定义的构造函数,它接受并存储对 OuterClass 的引用,这样:

struct Compare
{
Compare(OuterClass& o) : oc(o) { }
bool operator ()(const T&, const T&)
{
// Uses oc somehow...
}
private:
OuterClass& oc;
};

然后,当您创建集合时,您可以执行以下操作:

int main()
{
typedef std::set<T, Compare> MySet;

OuterClass oc; // <== Construct an object of type Outerclass somehow...

MySet ms(Compare(oc)); // <== Construct your comparator and pass it
// in input to the constructor of std::set
}

但请注意:排序标准应保持稳定。对于同一集合,元素必须始终比较相同。根据 C++11 标准的第 23.2.4/3 段:

The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.

关于C++ STL 集 : Compare object with extrinsic state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261441/

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