2017-01-23 37 views
1

給定一個對應於網格上城市位置的座標向量,如何生成這些點對象的每個置換?我懷疑使用預定義功能next_permutation使用用戶定義的類(在我的情況下,點)有問題。生成對象矢量的所有可能排列

#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())); 
} 
+3

['std :: next_permutation'](http://en.cppreference.com/w/cpp/algorithm/next_permutation) –

回答

1

幾件事情,

首先使用next_permutations容器必須進行排序。

秒爲比較兩個自定義對象的排序和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的副本以進行排列。

1

防爆片段:

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

我已經實現了上述內容,但是我得到了一些來自'xutility '文件。有任何想法嗎? –

+0

請確保您使用了正確的標題和命名空間。如果可能,請粘貼錯誤。 – MSD