【问题标题】:Generate All Possible Permutations of Vector of Objects生成对象向量的所有可能排列
【发布时间】:2017-01-23 04:08:52
【问题描述】:

给定一个与网格上的城市位置相对应的坐标向量,我如何生成这些点对象的每个排列?我怀疑在预定义函数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()));
}

【问题讨论】:

标签: c++ algorithm permutation


【解决方案1】:

几件事,

首先使用next_permutations的容器必须排序。

要比较两个自定义对象的 sort 和 next_permutations,您需要重载 &lt; 运算符。

这样的事情应该可以工作:

#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 的副本来进行排列。

【讨论】:

    【解决方案2】:

    前 sn-p:

    #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;
        }
    

    【讨论】:

    • 我已经实现了上述内容,但是我收到了来自“xutility”文件的几个错误。有什么想法吗?
    • 确保你使用了正确的标题和命名空间。如果可能的话,粘贴错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 2023-03-29
    • 2016-09-09
    • 1970-01-01
    相关资源
    最近更新 更多