fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using std::uint32_t;
  6. template< class RandomAccessIterator,class Compare >
  7. auto sort2(RandomAccessIterator begin,RandomAccessIterator end,Compare cmp) ->
  8. std::vector<std::pair<uint32_t,RandomAccessIterator>>
  9. {
  10. using valueType=typename std::iterator_traits<RandomAccessIterator>::value_type;
  11. using Pair=std::pair<uint32_t,RandomAccessIterator>;
  12.  
  13. std::vector<Pair> index_pair;
  14. index_pair.reserve(std::distance(begin,end));
  15.  
  16. for(uint32_t idx=0;begin!=end;++begin,++idx){
  17. index_pair.push_back(Pair(idx,begin));
  18. }
  19.  
  20. std::sort( index_pair.begin(),index_pair.end(),[&](const Pair& lhs,const Pair& rhs){
  21. return cmp(*lhs.second,*rhs.second);
  22. });
  23.  
  24. return index_pair;
  25. }
  26.  
  27. int main()
  28. {
  29. std::vector<int> a{1,7,3,4,8,4};
  30. auto sorted_pair=sort2(a.begin(),a.end(), std::greater<int>());
  31. for(uint32_t i=0;i<a.size();++i){
  32. std::cout<<"Last position : "<<sorted_pair[i].first<<
  33. "\tValue : "<<*sorted_pair[i].second<<'\n';
  34. }
  35. }
  36.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Last position : 4	Value : 8
Last position : 1	Value : 7
Last position : 3	Value : 4
Last position : 5	Value : 4
Last position : 2	Value : 3
Last position : 0	Value : 1