C++优先级队列中自定义比较器类复制构造函数的过度调用

cl25kdpy  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(163)

我已经声明了一个priority_queue,其中自定义比较器具有一个vector属性。下面是它的完整代码:

代码

#include <bits/stdc++.h>

using namespace std;

class Compare
{
private:
    vector<int> vec;

public:
    Compare(const vector<int> &vec) { this->vec = vec; }

    Compare(const Compare &obj)
    {
        this->vec = obj.vec;
        cout << "Copy Constructor Called!\n";
    }

    bool operator()(const int &left, const int &right)
    {
        return vec[left] > vec[right];
    }
};

int main(void)
{
    vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    priority_queue<int, vector<int>, Compare> pq{Compare(vec)};

    cout << "Pushing 1\n";
    pq.push(1);
    cout << "Pushed 1\n";
    cout << "Pushing 2\n";
    pq.push(2);
    cout << "Pushed 2\n";

    while (!pq.empty())
    {
        cout << "Popped = " << pq.top() << '\n';
        pq.pop();
    }
    return 0;
}

但是输出很奇怪!!

输出

Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Pushing 1
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Pushed 1
Pushing 2
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Pushed 2
Popped = 1
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Popped = 2
Copy Constructor Called!

为什么每次push和pop操作都要多次调用复制构造函数?
同样没有任何push或pop操作,当我只声明priority_queue时,复制构造函数被调用4次
为什么会发生这种情况?priority_queue存储比较器类对象并在需要比较时使用它,这难道不正确吗?

9bfwbjaz

9bfwbjaz1#

std::make_heap通过值see获取比较器,make_heaplibstdc++实现中的许多内部函数也是如此。libc++通过值传递less,但它确实做了一些。
比较器被认为是廉价的复制。如果它们需要外部数据,让它们存储指向外部数据的指针。

相关问题