我想探索二维点(二维数组中的 x、y 坐标)的所有排列 我的二维点结构是:
struct pos_t {
int x; int y;
pos_t(){x = 0 ; y = 0;}
pos_t(int X, int Y){x=X; y=Y;}
pos_t(pos_t const & r) {x = r.x; y=r.y;}
pos_t& operator=(pos_t const & r) {x = r.x; y=r.y; return *this;}
bool operator < ( pos_t& p2)
{
return (x+y) < (p2.x+p2.y);
}
friend ostream& operator << (ostream &o, const pos_t& p)
{
return o << "(" << p.x << "," << p.y << ")";
}
};
使用 pos_t vector 调用 treasurePos ( vector<pos_t>
),我使用下面的代码迭代其他不同的排列并显示每个排列。
do {
copy(begin(treasurePos), end(treasurePos), ostream_iterator<pos_t>(cout, " -> "));
cout << endl;
} while ( std::next_permutation(begin(treasurePos),end(treasurePos)) );
但是我的 vector 中有以下 pos_t 元素:(0,2) 和 (1,0)
我只得到一个排列:(0,2) -> (1,0) ->
我希望有:
(0,2) -> (1,0) ->
(1,0) -> (0,2) ->
另一个例子,有 4 个点,我只得到 2 个排列:
(1,3) -> (2,2) -> (3,0) -> (3,1) ->
(1,3) -> (2,2) -> (3,1) -> (3,0) ->
你有想法吗?
最佳答案
next_permutation
为 false
当新排列在字典序上不大于旧排列时。
由于您的订单显示 (1,0)
小于 (0,2)
,序列 {(1,0), (0 ,2)}
在字典序上小于 {(0,2), (1,0)}
,并且 next_permutation
为 false
立即。
您的四点示例背后也有同样的原因。
如果要遍历所有排列,则应先对序列进行排序。
关于c++ - 二维点的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380782/