C++ sorting and keeping track of indexes -


Using C ++, and hopefully standard library, I want to sort the order of the samples in ascending order, but I also want to remember the original indexes of new samples. For example, I have a set, or matrix of vector or samples A: [5, 2, 1, 4, 3] . I want to sort these by: B: [1,2,3,4,5] , but I have to remember the original index of values, so I can get another set which is: C: [2, 1, 4, 3, 0] - that matches the indicator of each element in 'A', in the original 'A' For example, you can do this in Matlab:

  [a, b] = sort ([5, 8, 7]) a = 5 7 8 b = 1 3 2  

Can anyone see a good way of doing this?

Using C ++ 11 Lambda

  template & lt ; Typename T & gt; The vector & lt; Size_t> Sort_indexes (const vector & lt; T & gt; & amp; v) {// Start original index locations vector & lt; Size_t> IDX (v.size ()); Item (idx.begin (), idx.end (), 0); // Sort sorted values ​​v variant (idx.begin (), idx.end (), [& amp; v] (size_t i1, size_t i2) {return v [i1] & lt; v [i2];} ); Return idx; }  

You can now re-index the vector in iterations like

 for  (auto i: sort_indexes (v)) {cout & Lt; & Lt; V [i] & lt; & Lt; Endl; }  

Obviously, you can choose to reorder your original index vector, sort function, comparator, or automatically into the sort_indexes function by using an additional vector.


Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -