Osama Belal
Osama Belal

Reputation: 46

Ordering array values while tracking their original position

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.

Upvotes: 2

Views: 100

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123566

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());

Upvotes: 1

Related Questions