Pythonのmapが便利なので、同じように使えそうなmapをC++14で作ってみました。
ソースはこちら。(勉強がてらなので、雑然としてます。)
サンプル: https://github.com/muumu/lib/blob/master/sample/sample_functional.cpp
ライブラリ: https://github.com/muumu/lib/blob/master/functional.h
以下、作ったfn::mapのだいたいの使用感です。
それぞれの要素に関数やメンバ関数を適用したコンテナを作る
{
vector<string> source = {"a?", "ab?", "abc?", "abcd?"};
auto output = fn::map(source, fn::init);
print(output); // {"a","ab","abc","abcd"}
}
{
list<string> source = {"", "occupied", "", "occupied"};
auto output = fn::map(source, &string::empty);
print(output); // {true,false,true,false}
}
{
array<string, 4> source = {"add", "sub", "mul", "div"};
auto output = fn::map(source, util::upper);
print(output); // {"ADD","SUB","MUL","DIV"}
}
違うデータ型になる関数はそのデータ型のコンテナに変換
{
set<string> source = {"tea", "wine", "milk", "coffee"};
auto output = fn::map(source, &string::size);
print(output); // {3,4,6}
}
{
multiset<string> source = {"tea", "wine", "milk", "coffee"};
auto output = fn::map(source, &string::size);
print(output); // {3,4,4,6}
}
キーとバリューを逆転したマップの作成
{
map<string, int> source_map = {{"RED", 0}, {"GREEN", 1}, {"BLUE", 2}};
auto reversed_map = fn::map(source_map, fn::swap<string, int>);
print(reversed_map); // {{0,"RED"},{1,"GREEN"},{2,"BLUE"}}
}
vectorの出力を違うコンテナで受け取る
{
multimap<string, int> src_map = {{"RED", 0}, {"RED", 0}, {"GREEN", 1}};
auto func = [](const pair<string, int>& pair) {
return pair.first + ": " + util::to_string(pair.second);};
auto result = fn::map(src_map, func);
print(result); // {"GREEN: 1","RED: 0","RED: 0"}
set<string> result_set = fn::map(src_map, func);
print(result_set); // {"GREEN: 1","RED: 0"}
}
0 件のコメント:
コメントを投稿