jmc*_*lem 6 c++ class vector permutation
是否可以使用std :: next_permutation()来置换我创建的类的向量元素?
next_permutation()中的compare参数如何工作?
Pra*_*rav 11
是否可以使用std :: next_permutation()来置换我创建的类的向量元素?
是!
试试这个
#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()));
}
Run Code Online (Sandbox Code Playgroud)
next_permutation()中的compare参数如何工作?
这可能有所帮助
是的,最简单的方法是在你的类中覆盖operator<,在这种情况下你不需要担心comp。
comp 参数是一个函数指针,它接受两个指向向量的迭代器,并根据您希望它们的排序方式返回 true 或 false。
编辑:未经测试,但就其价值而言:
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;
}
Run Code Online (Sandbox Code Playgroud)