vendredi 15 septembre 2023

why element in std::priority_queue deconstructed so many times?

I am using std::priority_queue to do file sort, which i think heap is the best way to sort the stream data.

here is the code:

#include <bits/stdc++.h>
using namespace std;

struct A { 
  A(int a, size_t b, double c) : a_(a), b_(b), c_(c){}
  ~A() { printf("%d dead\n", a_); }
  int a_; 
  size_t b_; 
  double c_; 
  bool operator <(const A & b) const {
    return a_ > b.a_;
  }
  void show() const {
    printf("%d %zu %lf\n", a_, b_, c_);
  }
};

int main() {
  std::priority_queue<A> q;
  q.push(A(1,2,3));
  q.push(A(3,2,3));
  q.push(A(2,2,3));
  while (!q.empty()) {
    const A & s = q.top();
    s.show();
    q.pop();
  }
}

the sorting process is good, but what made me surprised is the element deconstructed so many times as the output is :

1 dead
1 dead
1 dead
1 dead
3 dead
3 dead
3 dead
1 dead
3 dead
2 dead
2 dead
2 dead
1 2 3.000000
2 dead
2 dead
2 dead
1 dead
2 2 3.000000
3 dead
3 dead
3 dead
2 dead
3 2 3.000000
3 dead

i think every element should deconstruct once, could you explain this?

I think there are only 3 elements constructed, what i expected is only 3 times deconstruct. which i think there is no waste.

Aucun commentaire:

Enregistrer un commentaire