fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <queue>
  4. #include <vector>
  5.  
  6. struct Foo {
  7. Foo(int _a) : a(_a) {}
  8. int a;
  9. };
  10.  
  11. struct FooComparator {
  12. bool operator()(Foo *a, Foo *b) { return a->a < b->a; }
  13. };
  14.  
  15. int main() {
  16. std::list<Foo> foos;
  17. //std::vector<Foo> foos; // when used instead, the behaviour will become undefined
  18. std::priority_queue<Foo *, std::vector<Foo *>, FooComparator> pq;
  19.  
  20. // Simulate creation and 'containment' of objects, while they are being processed by other structures.
  21. for(int i=0; i<100; ++i) {
  22. foos.push_back(Foo((100-i) % 10));
  23. pq.emplace(&foos.back());
  24. }
  25.  
  26. while(not pq.empty()) {
  27. std::cout << pq.top()->a << " "; // the dereference -> may segfault if foos is not *pointer stable*
  28. pq.pop();
  29. }
  30.  
  31. std::cout << std::endl;
  32. return 0;
  33. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
9 9 9 9 9 9 9 9 9 9 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 4 4 4 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0