2

I want to keep track of the original position of the values after sorting them.

I saw a solution to this a while back but I lost it somewhere, it was done using a multi-set and pairs.

int x[2][2] = { {3, 2}, {1, 4}};

sorted_x = { {4,(1,1)}, {3,(0,0)}, {2,(0,1)}, {1,(1,0)} }; 

I have been trying for a few hours now and am unable to find it.

Maurycyt
  • 676
  • 3
  • 19
  • `int x[]` is a 1d array – 463035818_is_not_an_ai Aug 12 '21 at 09:52
  • [keeping track of the original indices of an array after sorting in C](https://stackoverflow.com/questions/24586499/keeping-track-of-the-original-indices-of-an-array-after-sorting-in-c) – Scratte Aug 12 '21 at 12:26
  • [Sort and keep track of elements](https://stackoverflow.com/questions/13248149/sort-and-keep-track-of-elements) – Scratte Aug 12 '21 at 12:27
  • [C++ sorting and keeping track of indexes](https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes) – Scratte Aug 12 '21 at 12:28
  • [Sorting an array without losing the original index in C](https://stackoverflow.com/questions/34864228/sorting-an-array-without-losing-the-original-index-in-c) – Scratte Aug 12 '21 at 12:31

1 Answers1

1

You can populate some container that contains the elements together with their index and then sort that:

struct element_and_index {
     int value;
     size_t x;
     size_t y;
     bool operator<(const element_and_index& other) const {
         return value < other.value;
     }
};

std::vector<element_and_index> temp;

// ... populate the vector ....

std::sort(temp.begin(),temp.end());
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 2
    The operator signature should have `const` after it for full utility, so `bool operator<(const element_and_index& other) const {`. For instance, if you used this in `std::priority_queue<>`, it wouldn't work. – Maurycyt Aug 12 '21 at 10:03