STL: nth_element为什么结果和sort一样?
#include <iostream>#include <algorithm>
#include <functional>
#include <vector>
#include <time.h>
using namespace std;
int Random(int low=0, int high=RAND_MAX)
{
return rand()%(high-low+1)+low;
}
bool exam(int x)
{
return x>=60;
}
int main()
{
int i;
vector<int> a;
vector<int> b;
srand((unsigned)time(0));
for (i=0; i<10; i++)
a.push_back(Random(1,100));
copy(a.begin(),a.end(),ostream_iterator<int>(cout,","));
cout<< endl;
b=a;
sort(b.begin(), b.end());
cout<< "sort: ";
copy(b.begin(),b.end(),ostream_iterator<int>(cout,","));
cout<< endl;
b=a;
sort(b.begin(), b.end(), greater<int>());
cout<< "sort(greater): ";
copy(b.begin(),b.end(),ostream_iterator<int>(cout,","));
cout<< endl;
b=a;
nth_element(b.begin(), b.begin()+3, b.end()); // 为什么结果和sort一样?
cout<< "nth_element: ";
copy(b.begin(),b.end(),ostream_iterator<int>(cout,","));
cout<< endl;
b=a;
partial_sort(b.begin(), b.begin()+3, b.end());
cout<< "partial_sort: ";
copy(b.begin(),b.end(),ostream_iterator<int>(cout,","));
cout<< endl;
vector<int> c(3);
b=a;
partial_sort_copy(b.begin(), b.end(), c.begin(), c.end());
cout<< "partial_sort_copy: ";
copy(c.begin(),c.end(),ostream_iterator<int>(cout,","));
cout<<" b: ";
copy(b.begin(),b.end(),ostream_iterator<int>(cout,","));
cout<< endl;
b=a;
partition(b.begin(), b.end(), exam);
cout<< "partition: ";
copy(b.begin(),b.end(),ostream_iterator<int>(cout,","));
cout<< endl;
return 0;
}