Last active
August 29, 2015 14:07
-
-
Save meki/08e9e10585ace595a58a to your computer and use it in GitHub Desktop.
STL コンテナを代入できる選択ソートテンプレート関数 ref: http://qiita.com/_meki/items/f655af1a911db7ee9798
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <list> | |
using namespace std; | |
//! 選択ソートテンプレート関数 | |
template <typename InIt, typename Pred> | |
void select_sort(InIt init, InIt last, Pred pred) | |
{ | |
for(InIt curr = init; curr != last; ++curr) | |
{ | |
InIt itMin = curr; | |
// curr 以降のデータ列中で最小の要素を探す | |
for(InIt it = curr; it != last; ++it) | |
{ | |
if(pred(*it, *itMin)) | |
{ | |
itMin = it; | |
} | |
} | |
// curr と見つかった最小要素の値を交換 | |
std::swap(*itMin, *curr); | |
} | |
} | |
// 実行例 | |
int main() | |
{ | |
// リストコンテナを定義 | |
std::list<int> lst = { 5, 4, 8, 7, 9, 1, 0 }; | |
cout << "最初\n"; | |
for(int i : lst) { cout << i << ", "; } | |
select_sort(lst.begin(), lst.end(), | |
[](const int& a, const int& b) -> bool | |
{ | |
// 昇順ソート | |
return a < b; | |
}); | |
cout << "\n\n昇順\n"; | |
for(int i : lst) { cout << i << ", "; } | |
select_sort(lst.begin(), lst.end(), | |
[](const int& a, const int& b) -> bool | |
{ | |
// 降順ソート | |
return a > b; | |
}); | |
cout << "\n\n降順\n"; | |
for(int i : lst) { cout << i << ", "; } | |
return 0; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
最初 | |
5, 4, 8, 7, 9, 1, 0, | |
昇順 | |
0, 1, 4, 5, 7, 8, 9, | |
降順 | |
9, 8, 7, 5, 4, 1, 0, | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment