小弟我发现nth_element的效果和sort一样啊似乎是全排序而不是只找到了最小/最大的n个
我发现nth_element的效果和sort一样啊,似乎是全排序而不是只找到了最小/最大的n个
下面这段代码在VC和GCC上编译运行结果是一样的:
2,3,4,4,7,9,15,27,29,
9,8,7,6,5,4,3,2,1,Press any key to continue . . .
不是说,nth_element只找出头n个最小(默认)或者最大(greater)的元素且不保证顺序么?
怎么我运行的结果看起来是sort那样的全排序呢?
------解决方案--------------------
数据太小。
在我机器上msvc2012输出34。
下面这段代码在VC和GCC上编译运行结果是一样的:
#include "stdafx.h"
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int buf[]={3,29,4,27,15,9,2,4,7};
nth_element(buf,buf+3,&buf[9]);
copy(buf,&buf[9],ostream_iterator<int>(cout,","));
cout << endl;
int buf2[]={1,2,3,4,5,6,7,8,9};
nth_element(buf2,buf2+5,&buf2[9],greater<int>());
copy(buf2,&buf2[9],ostream_iterator<int>(cout,","));
return 0;
}
2,3,4,4,7,9,15,27,29,
9,8,7,6,5,4,3,2,1,Press any key to continue . . .
不是说,nth_element只找出头n个最小(默认)或者最大(greater)的元素且不保证顺序么?
怎么我运行的结果看起来是sort那样的全排序呢?
------解决方案--------------------
数据太小。
for(n=2;n<5000;n++)
{
vector<int> v(n);
for(int i=0;i<n;i++)
v[i] = n-i;
nth_element(v.begin(), v.begin() + n/2, v.end());
bool cont = true;
for(int i=0;i<n;i++)
if(v[i] != i+1)
{
cont = false;
cout<<n<<endl;
break;
}
if(!cont)
break;
}
在我机器上msvc2012输出34。