Fu-koの足跡

コンピュータが苦手です。得体のしれない感じに抵抗があります。考えるのは好きです。すっきりしたロジックに感動します。ちゃんと理解すれば好きになれるはずと信じて、その過程を残そうと思います。

std::vectorのソート

std::vectorはstd::sortを使ってソートできる。
以下は簡単なソートの例。

<ソース>

#include <iostream>
#include <vector>
#include <algorithm>	// for std::sort
#include <functional>	// for std::greater

void main()
{
	std::vector<int> vec;
	vec.push_back(3);
	vec.push_back(1);
	vec.push_back(2);

	// 昇順ソート
	std::sort(vec.begin(), vec.end());
	for (int i = 0; i < vec.size(); i++) std::cout << vec.at(i) << std::endl;

	std::cout << std::endl;

	// 降順ソート
	std::sort(vec.begin(), vec.end(), std::greater<int>());
	for (int i = 0; i < vec.size(); i++) std::cout << vec.at(i) << std::endl;
}

<実行結果>

1
2
3

3
2
1

std::sortの第3引数に自前の比較関数を指定することで、
クラス型の要素のvectorもソートできる。