提问人:Neeraj-Kumar-Coder 提问时间:6/29/2023 更新时间:6/29/2023 访问量:59
过度调用 C++ 优先级队列中自定义比较器类的复制构造函数
Excessive Invocation of Copy Constructor for Custom Comparator Class in C++ Priority Queue
问:
我已经声明了一个带有自定义比较器的向量属性。以下是它的完整代码:priority_queue
法典
#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!
为什么复制构造函数在每次推送和弹出操作时都会被调用这么多次?
也没有任何推送或弹出操作,当我刚刚声明 时,复制构造函数被调用了 4 次priority_queue
为什么会这样?priority_queue存储比较器类对象并在需要比较时使用它,这难道不是正确的吗?
答:
评论
this