【问题标题】:C++ lambda function in priority_queue with capture by referencepriority_queue 中的 C++ lambda 函数,通过引用捕获
【发布时间】:2018-01-22 13:01:39
【问题描述】:

我正在解决一个算法问题 - “找到第 k 个丑数”,下面是问题陈述和我的实现。

Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 
For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

vector<int> tmp(1,1);
vector<int> primes({2,3,5});
vector<int> indices(3, 0);
// lambda function pass in variables are captured by reference
priority_queue<int, vector<int>, function<bool(const int&, const int&)>> pq([&](const int& a, const int& b){
    return primes[a] * tmp[indices[a]] > primes[b] * tmp[indices[b]];
});
pq.push(0); pq.push(1); pq.push(2);
while(tmp.size() <= 3) { // find the first three ugly number
    int primeIndex = pq.top();
    pq.pop();
    int nextval = primes[primeIndex] * tmp[indices[primeIndex]];
    pq.push(primeIndex + 1);
    indices[primeIndex]++;

    while(!pq.empty() && primes[pq.top()] & tmp[indices[pq.top()]]) {
        primeIndex = pq.top();
        pq.pop();
        pq.push(primeIndex + 1);
        indices[primeIndex]++;
    }
    cout << nextval << endl;
    tmp.push_back(nextval);
}
return 0;

priority_queue 的使用是对此解决方案的优化。 Priority_queue 在 O(logN) 时间内找到“下一个丑陋”的数字。 priority_queue 使用 primes[] 的索引作为其元素。它使用 lambda 函数作为比较器并通过引用捕获所有外部变量。我测试了我的代码以输出前 3 个丑陋的数字(应该是 2、3、4),但我的代码给了我“2、6、0”。我认为我在 priority_queue 中的 lambda 函数有问题,但我找不到原因。谁能给我一个解决我的错误的提示?非常感谢。

【问题讨论】:

    标签: algorithm lambda comparator priority-queue


    【解决方案1】:

    您的代码的直接问题是您访问的tmp 向量越界。您使用indices 的元素作为tmp 的索引,并在外部while 循环的迭代中的多个位置递增indices 的元素(一次在内部while 循环之前,并且可能在内部while 循环中一次或多次)内部 while 循环),并且您仅在外部 while 循环的迭代结束时增加 tmp 的大小。同时,在内部 while 循环的条件下,您可以在增加 tmp 的大小之前使用您可能已经增加(可能多次)的索引来索引 tmp

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 1970-01-01
      • 2013-07-26
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多