I have to perform the following task. Take a std::vector<float>
, sort the elements in descending order and have an indexing that maps the unsorted elements to the sorted ones. Please note that the order really matters: I need a map that, given the i-th element in the unsorted vector, tells me where this element is found in the sorted one. The vice-versa has been achieved already in a pretty smart way (through c++ lambdas) e.g., here: C++ sorting and keeping track of indexes. Nevertheless, I was not able to find an equally smart way to perform the "inverse" task. I would like to find a fast way, since this kind of mapping has to be performed many times and the vector has big size.
Please find in the following a simple example of what I need to achieve and my (probably suboptimal, since it relies on std::find
) solution of the problem. Is it the most fast/efficient way to perform this task? If not, are there better solutions?
Example
Starting vector: v = {4.5, 1.2, 3.4, 2.3}
Sorted vector: v_s = {4.5, 3.4, 2.3, 1.2}
What I do want: map = {0, 3, 1, 2}
What I do not want: map = {0, 2, 3, 1}
My solution
template <typename A> std::vector<size_t> get_indices(std::vector<A> & v_unsorted, std::vector<A> & v_sorted) {
std::vector<size_t> idx;
for (auto const & element : v_unsorted) {
typename std::vector<A>::iterator itr = std::find(v_sorted.begin(), v_sorted.end(), element);
idx.push_back(std::distance(v_sorted.begin(), itr));
}
return idx;
}
Thanks a lot for your time, cheers!