c++ - 二维点的排列

标签 c++ c++11

我想探索二维点(二维数组中的 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_permutationfalse 当新排列在字典序上不大于旧排列时。

由于您的订单显示 (1,0) 小于 (0,2),序列 {(1,0), (0 ,2)} 在字典序上小于 {(0,2), (1,0)},并且 next_permutationfalse 立即。

您的四点示例背后也有同样的原因。

如果要遍历所有排列,则应先对序列进行排序。

关于c++ - 二维点的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380782/

相关文章:

c++ - 如何在 C 或 C++ 中使用语句 block 定义函数?

c++ - 带有 std::vector 的信号和槽:左值问题

c++ - 不带下划线的用户定义文字

c++ - Abstract 和 Derived 与 std::list 结合

c++ - 递归文件搜索

内部类中的 C++ 模板运算符重载

c++ - 如何在 C++ 中做比率以及大于和小于

java - 如何在c++/java中生成一组遵循一定分布的值?

c++ - 如何加快大字符串的解析速度?

c++ - 为什么即使是 ""也必须使用 std::string() 来满足模板参数?