標準愚痴出力

個人的なIT作業ログです。もしかしたら一般的に参考になることが書いているかもしれません(弱気

std::vector / std::set 両方からデータを取れる関数をあまりテンプレートにしたくない

というような主旨のことを述べたら、boost::any_range をオススメされました。

が、弊社では外部ライブラリの導入がめんどくさいので、boost といえど、あまり使いたくない(未だに Visual Studio 2010 がメインに使われてるようなところだからね)

とすると、コールバック関数かなぁ

#include <iostream>
#include <vector>
#include <functional>
#include <set>

void put(std::function<bool(std::string&)> each)
{
    std::string value;
    while( each(value) ){
        std::cout << value << std::endl;
    }
}

int main()
{
    std::vector<std::string> v;
    v.push_back( "a" );
    v.push_back( "b" );
    v.push_back( "c" );

    auto p=v.begin();
    put( [&v,&p](std::string &value){ if( p == v.end() ){ return false; } value = *p ; p++ ; return true; } );

    std::set<std::string> s;
    s.insert( "a" );
    s.insert( "b" );
    s.insert( "c" );

    auto q=s.begin();
    put( [&s,&q](std::string &value){ if( q == s.end() ){ return false; } value = *q ; q++ ; return true; } );
}
$ gcc -std=c++14 it.cpp -lstdc++
$ a
a
b
c
a
b
c

うーん、呼び出しがすごく面倒くさい。

標準ライブラリに std::vector , std::set の既定クラス的な std::collection とか std::enumerable とかあればよかったのに。

本件、たぶん、続きます。