Use next_permutation to permutate a vector of classes

后端 未结 3 1876
[愿得一人]
[愿得一人] 2021-01-12 11:49

Is it possible to use std::next_permutation() to permutate the elements of a vector of a class i created?

How does the comparison parameter in next_permutation() wor

3条回答
  •  天涯浪人
    2021-01-12 12:18

    Yes, the simplest way is to override operator< within your class in which case you don't need to worry about comp.

    The comp parameter is a function pointer which takes two iterators to the vector and returns true or false depending on how you'd want them ordered.

    Edit: Untested but for what it's worth:

    class myclass
    {
    public:
        myclass() : m_a( 0 ){}
        void operator = ( int a ) { m_a = a; }
    
    private:
        friend bool operator<( const myclass& lhs, const myclass& rhs ) { return lhs.m_a < rhs.m_a; }
        int m_a;
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        myclass c;  
        std::vector vec;
    
        for( int i = 0; i < 10; ++i )
        {
            c = i;
            vec.push_back( c );
        }
    
        //these two should perform the same given the same input vector
        std::next_permutation( vec.begin(), vec.end() );    
        std::next_permutation( vec.begin(), vec.end(), &operator< );
    
        return 0;
    }
    

提交回复
热议问题