fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <functional>
  5.  
  6. struct gunman
  7. {
  8. int accuracy ;
  9. bool alive ;
  10. int position ;
  11. };
  12.  
  13. std::ostream& operator<< ( std::ostream& stm, const gunman& g )
  14. {
  15. return stm << "{ " << "accuracy:" << g.accuracy << ", position:" << g.position
  16. << ", alive:" << std::boolalpha << g.alive << " }" ;
  17. }
  18.  
  19. int main()
  20. {
  21. std::vector<gunman> gmen { {7,true,0}, {0,false,1}, {3,true,2}, {5,true,3},
  22. {2,false,4}, {4,true,5}, {0,false,6}, {7,true,7} } ;
  23. for( const auto& g : gmen ) std::cout << g << '\n' ;
  24. std::cout << "-----------------\n" ;
  25.  
  26. const auto cmp1 = [] ( const gunman &lhs , const gunman &rhs )
  27. {
  28. if( lhs.alive && rhs.alive ) return lhs.accuracy < rhs.accuracy ;
  29. else return lhs.alive ;
  30. };
  31.  
  32. auto position1 = std::min_element( gmen.begin() , gmen.end() , cmp1 )->position ;
  33. std::cout << "position of least accurate and alive: " << position1 << '\n' ;
  34.  
  35. const auto cmp2 = [position1,cmp1] ( const gunman &lhs , const gunman &rhs )
  36. { return cmp1(lhs,rhs) && ( lhs.position != position1 ) ; };
  37. auto position2 = std::min_element( gmen.begin() , gmen.end() , cmp2 )->position ;
  38. std::cout << "position of second-least accurate and alive: " << position2 << '\n' ;
  39.  
  40. std::cout << "-----------------\n" ;
  41.  
  42. std::vector< std::reference_wrapper<gunman> > tvec( gmen.begin() , gmen.end() ) ;
  43. std::sort( tvec.begin(), tvec.end(), cmp1 ) ;
  44. for( const auto& g : tvec ) std::cout << g << '\n' ;
  45. }
  46.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
{ accuracy:7, position:0, alive:true }
{ accuracy:0, position:1, alive:false }
{ accuracy:3, position:2, alive:true }
{ accuracy:5, position:3, alive:true }
{ accuracy:2, position:4, alive:false }
{ accuracy:4, position:5, alive:true }
{ accuracy:0, position:6, alive:false }
{ accuracy:7, position:7, alive:true }
-----------------
position of least accurate and alive: 2
position of second-least accurate and alive: 5
-----------------
{ accuracy:3, position:2, alive:true }
{ accuracy:4, position:5, alive:true }
{ accuracy:5, position:3, alive:true }
{ accuracy:7, position:0, alive:true }
{ accuracy:7, position:7, alive:true }
{ accuracy:0, position:1, alive:false }
{ accuracy:2, position:4, alive:false }
{ accuracy:0, position:6, alive:false }