ネタ元はこちら→文字列の配列への格納について
練習問題
「文字列 "1.23", "2.34", ... が詰まった可変長配列があって、
そいつの各要素をdoubleに変換して双方向リストに詰めよ」
C++ならこんな感じかな:
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
double s2d(const string& s) {
return std::atof(s.c_str());
}
int main() {
string data[] = { "1.23", "2.34", "3.45", "4.56" };
vector<string> input(data, data+4);
list<double> output;
transform(input.begin(), input.end(), back_inserter(output), &s2d);
copy(output.begin(), output.end(), ostream_iterator<double>(cout,"\n"));
}
transform()を使ってvector<string>の各要素に変換カマしつつlist<double>に挿入する、と。
これがC#、つか.NET Frameworkだと
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<string> input = new List<string>(new string[] { "1.23", "2.34", "3.45", "4.56" });
LinkedList<double> output = new LinkedList<double>(System.Array.ConvertAll<string,double>( input.ToArray(), delegate (string x) { return double.Parse(x); }));
foreach ( double value in output ) Console.WriteLine(value);});
}
}
…なーんかエレガントじゃねぇです。
List<string>をToArray()で配列にして、配列のGenericメソッドConvertAll()でdouble配列こさえて、そいつを引数にLinkedList<double>をnewする。
変換元がList<T>だから無問題なんだけど、これがLinkedList<T>だったりするとToArray()を持ってないのでひと手間かかる。コンテナとメソッドに直交性がないのよね。
C++版なら変換元/先のvectorとlistをひっくり返してもそのまーんま使えるのに。
ちょっとしたことなんだけど、STL慣れした僕には居心地が悪いっす。