Use next_permutation to permutate a vector of classes

女生的网名这么多〃 提交于 2019-12-19 07:23:27

问题


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() work?


回答1:


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

Yes!

Try this

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

int main()
 {
      typedef std::vector<int> V; //<or_any_class>
      V v;

      for(int i=1;i<=5;++i)
        v.push_back(i*10);
      do{
            std::cout<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<" "<<v[4]<<std::endl;;
        }

       while(std::next_permutation(v.begin(),v.end()));
 }

How does the comparison parameter in next_permutation() work?

This might help




回答2:


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<myclass> 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;
}



回答3:


  1. Sure thing; you just need to pass an iterator to the first element and one to the one-after-last element, as usual with STL algorithms.

  2. It's a functor used to compare elements of your vector (or container in general); it should behave as any < operator would do: return true if the first element is less than the second, false otherwise, thus establishing an order relation between your objects. Note that, as all the comparison operators, it must follow some rules (here explained in a slightly different context, but they are always the same).

By the way, if you define a < operator for your class you can simply use the first overload (the one with just the iterators as parameters) and avoid creating a separate functor.



来源:https://stackoverflow.com/questions/3184893/use-next-permutation-to-permutate-a-vector-of-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!