あめだまふぁくとりー

Boost.Graphとかできますん

ぷろぱてぃーまっぷ

BGL等でproperty mapを使っていると,たまにproperty mapをfunctorとして扱いたいときがある.そんなときにはproperty_map_funcionが使える.property_map_functionはproperty mapをfunctorとして扱うためのラッパオブジェクト.make_property_map_function関数を用いて受け取れる.受け取ったfunctorは渡したproperty mapのkey_typeを引数にとる.

#include <iostream>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <boost/graph/adjacency_list.hpp>
#include <boost/property_map/property_map.hpp> // for make_property_map_function

using namespace boost;
using namespace std;

int main()
{
	typedef adjacency_list<vecS, vecS, undirectedS,
			no_property, property<edge_weight_t, int> > Graph;

	enum { A, B, C, D, E, F, NumV };
	typedef std::pair<int, int> Edge;
	Edge edge_array[] = {
		Edge(A, B), Edge(A, D), Edge(A, E),
		Edge(B, C), Edge(B, D), Edge(B, F),
		Edge(C, D), Edge(C, F),
		Edge(D, E), Edge(E, F),
		Edge(E, F)
	};
	const int NumE = sizeof(edge_array) / sizeof(edge_array[0]);
	int edge_w[NumE] = {
		3, 4, 2, 5, 9, 3, 9, 2, 4, 5, 9
	};

	Graph g(edge_array, edge_array + NumE, edge_w, NumV);

	std::transform(edges(g).first, edges(g).second,
			std::ostream_iterator<int>(std::cout, " "),
			make_property_map_function(get(edge_weight, g)));
	std::cout << std::endl;

	return 0;
}

出力はこうなる.

3 4 2 5 9 3 9 2 4 5 9

property_map_functionはtransform_iteratorにも渡せるのでとても便利.