Created
June 21, 2020 07:23
-
-
Save HViktorTsoi/58eabb4f7c5a303ced400bcfa816f6f5 to your computer and use it in GitHub Desktop.
C++ STL implementation of Argsort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <algorithm> | |
/** | |
* Argsort(currently support ascending sort) | |
* @tparam T array element type | |
* @param array input array | |
* @return indices w.r.t sorted array | |
*/ | |
template<typename T> | |
std::vector<size_t> argsort(const std::vector<T> &array) { | |
std::vector<size_t> indices(array.size()); | |
std::iota(indices.begin(), indices.end(), 0); | |
std::sort(indices.begin(), indices.end(), | |
[&array](int left, int right) -> bool { | |
// sort indices according to corresponding array element | |
return array[left] < array[right]; | |
}); | |
return indices; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment