2017-10-27 4 views
-2

ベクトルのk番目の点(x座標)を取得するためにベクトルの順序を変更しようとしています。nth_elementを使用してk番目の点を(x座標で)取得しますが、動作しません。

k番目の要素の前には、k-1個の要素(ソートされていない)があり、xの値はk-thより小さい です。

k番目の要素の後、NK要素(ソートされていない)があるxの値がk番目のより大きい。(nは総要素数である)

私はこれを行うためにnth_elementを使用するが、出力まだ同じ。 誰でも私にその理由を教えてもらえますか?

何らかの理由で、私はソートを使いたくないです。

#include<iostream> 
#include<vector> 
#include<algorithm> 

using namespace std; 

class point{ 
    public: 
     int x, y; 
}; 

bool pCmpX(point a, point b){ //compare points with x-coordinate 
    return a.x<b.x; 
} 

void outPoint(point a){ 
    cout << "(" << a.x << "," << a.y << ")"; 
    return; 
} 

void getMed(vector<point> p){ 
    nth_element(p.begin(), p.begin()+4, p.end(), pCmpX); 
    return; 
} 

int main(){ 
    vector<point> set; 

    for(int i=0; i<10; i++){ 
     point a; 
     a.x = i; 
     a.y = i; 
     set.push_back(a); 
    } 

    random_shuffle (set.begin(), set.end());  //make point arrange random 

    for(vector<point>::iterator pItr=set.begin(); pItr!=set.end(); pItr++){ 
     outPoint(*pItr);  //print vector before using nth_element 
    } 
    cout << " \n"; 

    getMed(set); 

    for(vector<point>::iterator pItr=set.begin(); pItr!=set.end(); pItr++){ 
     outPoint(*pItr);  //print vector after using nth_element 
    } 
    cout << "\n"; 
    return 0; 
} 
+4

_役に立たない問題の説明ではありません。問題を再現する[MCVE]を提供し、問題を適切に記述します。 – user0042

答えて

0

getMed関数には、値のポイントを持つベクトルを渡します。その結果、ベクトルのgetMedのローカルコピーのn番目の要素が見つかります。

void getMed(vector<point>& p){ 
+0

Omg、ありがとう 私はベクトルと配列を混ぜる – CodePurin

関連する問題