我一直在研究std::nth_element算法,显然:
重新排列范围[first,last)中的元素,使得结果第n个位置的元素是排序序列中该位置的元素,其前面的元素都不大于,后面的元素也都不小于它。它前面的元素和后面的元素都不保证是有序的。
但是,使用我的编译器,运行以下命令:
vector<int> myvector;
srand(GetTickCount());
// set some values:
for ( int i = 0; i < 10; i++ )
myvector.push_back(rand());
// nth_element around the 4th element
nth_element (myvector.begin(), myvector.begin()+4, myvector.end());
// print results
for (auto it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
始终以与std::sort完全相同的方式返回完全排序的整数列表。我是不是遗漏了什么?这个算法有什么用呢?
编辑:好的,下面的例子使用了一个更大的集合,显示出有很大的区别:
vector<int> myvector;
srand(GetTickCount());
// set some values:
for ( int i = 0; i < RAND_MAX; i++ )
myvector.push_back(rand());
// nth_element around the 4th element
nth_element (myvector.begin(), myvector.begin()+rand(), myvector.end());
vector<int> copy = myvector;
std::sort(myvector.begin(), myvector.end());
cout << (myvector == copy ? "true" : "false") << endl;
https://stackoverflow.com/questions/10352442
复制相似问题