私はstd::nth_elementアルゴリズムを見てきました。
結果のn番目の位置にある要素が、ソートされたシーケンスでその位置にある要素になるように、範囲[first、last)の要素を再配置します。その前の要素はどれも大きくなく、それに続く要素はそれよりも小さい。その前の要素も後の要素も順序付けが保証されていません。
ただし、私のコンパイラでは、次のコマンドを実行します。
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;