2017-01-23 8 views
1

グリッド上の都市の位置に対応する座標ベクトルが与えられた場合、どのようにこれらの点オブジェクトのすべての順列を生成できますか?私は定義済みの関数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())); 
} 
+3

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

答えて

1

物事のカップル、コンテナがソートされなければならないnext_permutationsを使用する

最初。

2番目の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のコピーを作成します。

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

関連する問題