hoge diary - July 24, 2007

[C++] STL を未だに賢く使えていない自分

以下のようなファイルのデータを読み込んでコンテナに格納して,それを標準出力へ出力するプログラムを書くとします.

1 2 3
4 5 6

私がすっと思いつくのが以下のコード.

#include <iostream>
#include <fstream>
#include <list>
#include <functional>
#include <memory>

typedef int Value
typedef std::list<Value> DataContainer

//! ファイルからデータを読み出す
std::auto_ptr<DataContainer> Read(const std::string& filename)
{
    std::auto_ptr<DataContainer> data(new DataContainer);
    std::ifstream in(filename.c_str());

    for (;;)
    {
        int value;
        in >> value;
        if (!in) break;
        data->push_back(value);
    }

    return data;
}

//! データをストリームに書き出す
struct Show : public std::binary_function<int, std::ostream*, void>
{
    void operator () (int value, std::ostream* out) const
    { *out << value << "\n"; }
};

int main(int argc, char* argv[])
{
    std::auto_ptr<DataContainer> data = Read(argv[1]);
    std::for_each(data->begin(), data->end(), std::bind2nd(Show(), &std::cout));
    return 0;
}

とはいえ,Effective STL を読んでいると,std::list のコンストラクタで直接読み込んでいたりするので,上のコードではまだ車輪の再発明をしているわけです.

それを考慮して書き直したのが下のコード.

#include <iostream>
#include <fstream>
#include <iterator>
#include <list>
#include <functional>
#include <memory>

typedef int Value
typedef std::list<Value> DataContainer

//! ファイルからデータを読み出す (STL をより賢く使ったバージョン)
std::auto_ptr<DataContainer> Read(const std::string& filename)
{
    std::ifstream in(filename.c_str());
    std::istream_iterator<Value> in_begin(in);
    std::istream_iterator<Value> in_end;
    return std::auto_ptr<DataContainer>(new DataContainer(in_begin, in_end));
}

int main(int argc, char* argv[])
{
    std::auto_ptr<DataContainer> data = Read(argv[1]);
    std::copy(data->begin(), data->end(), std::ostream_iterator<Value>(std::cout, "\n"));
    return 0;
}

何と,Read() 関数はたった 4 行... 恐るべし STL.ちなみに実行結果はどちらのコードを用いても同じで,以下の通りの結果です.

1
2
3
4
5
6

コメント

名前(何でも可):

テキスト(http:// を含む内容は投稿できません):

トラックバック

トラックバック URI: https://www.pakunet.jp/hoge/trackback/2007072401

トラックバックはありません.


Valid XHTML 1.1! Valid CSS!
© 2004-2009 ぱくちゃん.
Last modified: Fri Nov 02 08:58:03 JST 2007