ネタ元 → 動的言語のなんとやら 2
標準C++ライブラリのヘッダ<numeric> に関数 accumulate が定義されています。
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
using namespace std;
int main() {
const char* input[] = {
"寿限無、寿限無 ", "五劫の擦り切れ ",
"海砂利水魚の ", "水行末 雲来末 風来末 " };
vector<string> words(input, input+4);
string jugem = accumulate(words.begin(), words.end(), string());
cout << jugem << endl;
}
accumulateはこんな感じ↓の実装。
template<typename Iterator, typename T>
T acumulate(Iterator first, Iterator last, T value) {
while ( first != last ) {
value = value + *first;
++first;
}
return value;
}
範囲[first,last)にある要素をvalueに積算してくれるですね。
.NetのGenericsは(アヒルが苦手なので)コレができましぇん。
「Tは+演算が適用できるんだよ」って制約を組み入れなくてはならんのだけど、
(オノレが用意するclass/stringならともかくも) intやstringがその制約を満たすってこと
を示すことができません。
演算を外出しすればなんとかなるですね。
using System;
using System.Collections.Generic;
class Program {
delegate T BinaryFunction<T>(T arg1, T arg2);
static T accumulate<T>(IEnumerable<T> container, T value, BinaryFunction<T> func) {
foreach ( T item in container ) {
value = func(value,item);
}
return value;
}
static void Main() {
string[] words = {
"寿限無、寿限無 ", "五劫の擦り切れ ",
"海砂利水魚の ", "水行末 雲来末 風来末 " };
string jugem = accumulate(words, "",
delegate(string x, string y) { return x + y; });
Console.WriteLine(jugem);
}
}