fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. struct Data
  5. {
  6. int key;
  7. int original_index;
  8. };
  9.  
  10. bool compare_with_itself_called = false;
  11. bool pointer_order_changed = false;
  12.  
  13. int compare(const void *p1, const void *p2)
  14. {
  15. if(p1==p2)
  16. {
  17. compare_with_itself_called = true;
  18. return 0;
  19. }
  20. const Data *d1 = (const Data*)p1;
  21. const Data *d2 = (const Data*)p2;
  22. if(d1->key < d2->key)
  23. return -1;
  24. if(d2->key < d1->key)
  25. return 1;
  26. bool index_cond = d1->original_index<d2->original_index;
  27. bool ptr_cond = (p1<p2);
  28. if(index_cond!=ptr_cond)
  29. {
  30. pointer_order_changed = true;
  31. }
  32. return index_cond ? -1 : 1;
  33. }
  34.  
  35. void outputArray(Data d[], unsigned n)
  36. {
  37. for(unsigned i=0; i!=n; ++i)
  38. std::cout << d[i].key << "@" << d[i].original_index << std::endl;
  39. }
  40.  
  41. int main()
  42. {
  43. const unsigned N = 4;
  44. Data array[N] = { { 8, 0 }, { 8, 1 }, { 1, 2 }, { 1, 3 } };
  45. qsort(array, N, sizeof(Data), compare);
  46. outputArray(array, N);
  47. std::cout << std::endl << "compare_with_itself_called="
  48. << (compare_with_itself_called ? "true" : "false") << std::endl;
  49. std::cout << "pointer_order_changed="
  50. << (pointer_order_changed ? "true" : "false") << std::endl;
  51. return 0;
  52. }
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
1@2
1@3
8@0
8@1

compare_with_itself_called=false
pointer_order_changed=false