我正在尝试重新排序矢量以在矢量中获得第k个点(通过x坐标)。
在第k个元素之前,有k-1个元素(未排序),x值较小 而不是k-th。
在第k个元素之后,有n-k个元素(未排序),x值大于第k个。(n是总元素数)
我使用nth_element来做到这一点,但输出仍然相同。 谁能告诉我为什么?
出于某种原因,我不想使用sort。
#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;
}
答案 0 :(得分:0)
您将带有点值的矢量传递给getMed
函数。因此,您可以在getMed
的向量本地副本中找到第n个元素。你应该通过引用传递它
void getMed(vector<point>& p){