#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

struct gunman
{
   int accuracy ;
   bool alive ;
   int position ;
};

std::ostream& operator<< ( std::ostream& stm, const gunman& g )
{
    return stm << "{ " << "accuracy:" << g.accuracy << ", position:" << g.position
               << ", alive:" << std::boolalpha << g.alive << " }" ;
}

int main()
{
    std::vector<gunman> gmen { {7,true,0}, {0,false,1}, {3,true,2}, {5,true,3},
                                {2,false,4}, {4,true,5}, {0,false,6}, {7,true,7} } ;
    for( const auto& g : gmen ) std::cout << g << '\n' ;
    std::cout << "-----------------\n" ;

    const auto cmp1 = [] ( const gunman &lhs , const gunman &rhs )
    {
        if( lhs.alive && rhs.alive ) return lhs.accuracy < rhs.accuracy ;
        else return lhs.alive ;
    };

    auto position1 = std::min_element( gmen.begin() , gmen.end() , cmp1 )->position ;
    std::cout << "position of least accurate and alive: " <<  position1 << '\n' ;

    const auto cmp2 = [position1,cmp1] ( const gunman &lhs , const gunman &rhs )
                       { return cmp1(lhs,rhs) && ( lhs.position != position1 ) ;  };
    auto position2 = std::min_element( gmen.begin() , gmen.end() , cmp2 )->position ;
    std::cout << "position of second-least accurate and alive: " <<  position2 << '\n' ;

    std::cout << "-----------------\n" ;

    std::vector< std::reference_wrapper<gunman> > tvec( gmen.begin() , gmen.end() ) ;
    std::sort( tvec.begin(), tvec.end(), cmp1 ) ;
    for( const auto& g : tvec ) std::cout << g << '\n' ;
}
