美文网首页
C++ list shuffle

C++ list shuffle

作者: delta1037 | 来源:发表于2021-05-12 11:04 被阅读0次
    // 来源:http://www.cplusplus.com/forum/general/207328/
    template < typename T > void list_shuffle( std::list<T>& lst ) // shuffle contents of a list
    {
        // create a vector of (wrapped) references to elements in the list
        // http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
        std::vector< std::reference_wrapper< const T > > vec( lst.begin(), lst.end() ) ;
    
        // shuffle (the references in) the vector
        std::shuffle( vec.begin(), vec.end(), std::mt19937{ std::random_device{}() } ) ;
    
        // copy the shuffled sequence into a new list
        std::list<T> shuffled_list {  vec.begin(), vec.end() } ;
    
        // swap the old list with the shuffled list
        lst.swap(shuffled_list) ;
    }
    

    相关文章

      网友评论

          本文标题:C++ list shuffle

          本文链接:https://www.haomeiwen.com/subject/mwfadltx.html