繁体   English   中英

C++ STL make_heap 和 priority_queue 给出不同的输出

[英]C++ STL make_heap and priority_queue gives different output

这是我的代码:

std::priority_queue<SimpleCycle,
                    std::vector<SimpleCycle>,
                    SimpleCycle> pq;
pq.push(cycle1);
pq.push(cycle2);
pq.push(cycle4);
std::cout << pq.top().to_string() << std::endl;

std::vector<SimpleCycle> pq2{ cycle1, cycle2, cycle4 };
std::make_heap(pq2.begin(), pq2.end(), SimpleCycle());
std::cout << pq2.front().to_string() << std::endl;

SimpleCycle比较器如下:

const bool SimpleCycle::operator()(SimpleCycle& L, SimpleCycle& R) const
{
    float a = L.avg_latency();
    float b = R.avg_latency();
    //Allow an error rate of 0.0000000001
    //Ref. The Art of Computer Programming: Seminumerical algorithms(Page 128)
    return (b - a) > ((fabs(a) < fabs(b) 
                    ? fabs(b) : fabs(a)) * (0.0000000001));
}

函数avg_latency()返回一个float 但是对于相同的输入案例,我得到了不同的输出。 可能有什么问题?

由于您的比较运算符“允许 0.0000000001 的错误率”,因此它不是 C++ 概念(例如http://en.cppreference.com/w/cpp/concept/Compare )定义的严格弱排序。

特别是,没有满足严格弱排序的对称性要求。 例如,如果我们将e称为错误阈值(在您的情况下为 0.0000000001),我们会看到:

  • SimpleCycle()(1 / e, 1 / e + 1)返回false
  • SimpleCycle()(1 / e + 1, 1 / e)返回false

Igor Tandenik 在评论中指出的另一个问题是,它引发的等价关系不是可传递的:a 可能与 b 足够接近,b 与 c 足够接近,但 a 与 c 不够接近。

根据cycle变量中的数据,这可能会导致priority_queuemake_heap方法返回的最大元素略有不同

也可能存在舍入错误...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM