Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <array>
  4.  
  5. template <typename Iter, typename Compare>
  6. std::vector<int> argsort(Iter begin, Iter end, Compare comp)
  7. {
  8. // Begin Iterator, End Iterator, Comp
  9. std::vector<std::pair<int, Iter> > pairList; // Pair Vector
  10. std::vector<int> ret; // Will hold the indices
  11.  
  12. int i = 0;
  13. for (auto it = begin; it < end; it++)
  14. {
  15. std::pair<int, Iter> pair(i, it); // 0: Element1, 1:Element2...
  16. pairList.push_back(pair); // Add to list
  17. i++;
  18. }
  19. // Stable sort the pair vector
  20. std::stable_sort(pairList.begin(), pairList.end(),
  21. [comp](std::pair<int, Iter> prev, std::pair<int, Iter> next) -> bool
  22. {return comp(*prev.second, *next.second); } // This is the important part explained below
  23. );
  24.  
  25. /*
  26. Comp is a templated function pointer that makes a basic comparison
  27. std::stable_sort takes a function pointer that takes
  28. (std::pair<int, Iter> prev, std::pair<int, Iter> next)
  29. and returns bool. We passed a corresponding lambda to stable sort
  30. and used our comp within brackets to capture it as an outer variable.
  31. We then applied this function to our iterators which are dereferenced.
  32. */
  33. for (auto i : pairList)
  34. ret.push_back(i.first); // Take indices
  35.  
  36. return ret;
  37. }
  38. int main()
  39. {
  40. std::array<int, 5> arr{ { 1, 11, 3, 2, -1 } }; // Array container
  41.  
  42. auto indices = argsort(arr.begin(), arr.end(), std::less<int>());
  43. // Use std::less functor to make an ASC sort
  44. for (auto i : indices)
  45. std::cout << i << std::endl; // Print
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement