fork(1) download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct MyOwnClass { int score; };
  6.  
  7. std::size_t get_index_of_nth_greatest(const std::vector<MyOwnClass>& v, std::size_t k)
  8. {
  9. std::vector<std::size_t> indexes(v.size());
  10. std::iota(indexes.begin(), indexes.end(), 0);
  11.  
  12. std::nth_element(indexes.begin(), indexes.begin() + k, indexes.end(),
  13. [&](int lhs, int rhs)
  14. {
  15. return v[lhs].score > v[rhs].score;
  16. }
  17. );
  18. return indexes[k];
  19. }
  20.  
  21.  
  22. int main()
  23. {
  24. std::vector<MyOwnClass> scores = {{2}, {42}, {5}, {21}, {1}, {3}};
  25.  
  26. for (std::size_t i = 0; i != scores.size(); ++i) {
  27. const auto index = get_index_of_nth_greatest(scores, i);
  28. std::cout << i << "th greater is at index " << index
  29. << " with value " << scores[index].score << std::endl;
  30. }
  31. }
  32.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
0th greater is at index 1 with value 42
1th greater is at index 3 with value 21
2th greater is at index 2 with value 5
3th greater is at index 5 with value 3
4th greater is at index 0 with value 2
5th greater is at index 4 with value 1