给定与网格上城市位置对应的坐标向量,如何生成这些点对象的每个排列?我怀疑使用预定义函数next_permutation
的用户定义类(在我的情况下为Point)存在问题。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Point
{
public:
double x, y;
Point(int x, int y);
friend ostream& operator<< (ostream &out, const Point &p);
};
Point::Point(int xCoord, int yCoord)
{
x = xCoord;
y = yCoord;
}
ostream& operator<< (ostream &out, const Point &p)
{
out << "(" << p.x << ", " << p.y << ")";
return out;
}
int main()
{
vector<Point> points = { {3,5}, {10,1}, {2,6} };
do
{
for (Point pt : points)
{
cout << pt << " ";
}
cout << endl;
} while (next_permutation(points.begin(), points.end()));
}
答案 0 :(得分:1)
Ex片段:
#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()));
return 0;
}
答案 1 :(得分:1)
有几件事,
首先使用next_permutations
必须对容器进行排序。
第二个比较sort和next_permutations的两个自定义对象,你需要重载<
运算符。
这样的事情应该有效:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Coords
{
public:
int x = 0;
int y = 0;
//This uses a simple lexicographical ordering, modify to suit your needs.
bool operator <( const Coords& rhs )
{
if ( x == rhs.x )
{
return y < rhs.y;
}
else
{
return x < rhs.x;
}
}
};
vector<vector<Coords>> GetPermutaions( vector<Coords>& vec )
{
vector < vector<Coords>> outVal ;
//if you can guarantee vec will be sorted this can be omitted
sort( vec.begin() , vec.end() );
do
{
outVal.emplace_back( vec );
} while ( next_permutation( vec.begin() , vec.end() ) );
return outVal;
}
有一点需要记住,这个函数会让vec处于排序状态。如果您需要原始状态,请创建一个vec副本以进行排列。