C++ sorting and keeping track of indexes -


using c++, , standard library, want sort sequence of samples in ascending order, want remember original indexes of newly samples.

for example, have set, or vector, or matrix of samples a : [5, 2, 1, 4, 3]. want sort these b : [1,2,3,4,5], want remember original indexes of values, can set be: c : [2, 1, 4, 3, 0 ] - corresponds index of each element in 'b', in original 'a'.

for example, in matlab can do:

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

can see way this?

using c++11 lambdas

template <typename t> vector<size_t> sort_indexes(const vector<t> &v) {    // initialize original index locations   vector<size_t> idx(v.size());   iota(idx.begin(), idx.end(), 0);    // sort indexes based on comparing values in v   sort(idx.begin(), idx.end(),        [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});    return idx; } 

now can use returned index vector in iterations such as

for (auto i: sort_indexes(v)) {   cout << v[i] << endl; } 

obviously, can choose supply own original index vector, sort function, comparator, or automatically reorder v in sort_indexes function using vector.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -