Use next_permutation to swap class vectors

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

How does the comparison parameter in next_permutation () work?

+6
c ++ class vector permutation
source share
3 answers

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

Yes!

try it

#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 can help

+8
source share

Yes, the easiest way is to override the <operator in your class, in which case you do not need to worry about comp.

The comp parameter is a function pointer that wraps two iterators into a vector and returns true or false depending on how you want them to be ordered.

Edit: Unverified, but what it costs:

 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; } 
+4
source share
  • Sure thing; you just need to pass the iterator to the first element, and one to the after-last element, as usual, with STL algorithms.

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

By the way, if you define an <operator for your class, you can simply use the first overload (one that has only iterators as parameters) and not create a separate functor.

+3
source share

All Articles