元のソースで
20. x = aa[p.second];
21. for(auto &elem : x) cout << elem << " ";
となってるところを

20. valarray<int> y = aa[p.second];
21. for(auto &elem : y) cout << elem << " ";
に変えてみ。

18.行で作ったx(要素は4個{1,2,3,4})に 20.行で要素1個{5}を先頭に入れても
残りの要素3個{2,3,4}は変化せずに残ってるのだと思われる。