Boost :: tuple相当于Python的itemgetter?

时间:2009-08-24 04:32:09

标签: c++ boost boost-tuples

我有一些看起来像这样的代码:

typedef tuple<int, int, double> DataPoint;
vector<DataPoint> data;
vector<double> third_column_only;
// Code to read in data goes here.
transform(data.begin(), data.end(), back_inserter(values), tuples::get<1, DataPoint>);

不幸的是,最后一行没有编译 - 它给我一条这样的信息:

/path/to/boost/tuple/detail/tuple_basic.hpp: In instantiation of `boost::tuples::cons':
/path/to/boost/tuple/detail/tuple_basic.hpp:144:   instantiated from `boost::tuples::element >'
program.cc:33:   instantiated from here
/path/to/boost/tuple/detail/tuple_basic.hpp:329: error: `boost::tuples::cons::tail' has incomplete type
/path/to/boost/tuple/detail/tuple_basic.hpp:329: error: invalid use of template type parameter
/path/to/boost/tuple/detail/tuple_basic.hpp:151: confused by earlier errors, bailing out

基本上,要使用Python的operator.itemgetter函数,我想做这样的事情:

transform(data.begin(), data.end(), back_inserter(values), itemgetter(2))  

如何使用Boost做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要boost::bind才能执行此操作。

double get2(boost::tuple<int,int,double> const& v ) {
    return boost::get<2>(v) ;
}

int main () {
    using namespace std ;
    using namespace boost ;
    typedef tuple<int, int, double> DataPoint;
    vector<DataPoint> data;
    vector<double> third_column_only;
    // Code to read in data goes here.
    transform(data.begin(), data.end(), back_inserter(values), bind(get2, _1);
}

实际上,get2函数也是不必要的,但我们必须为boost::get函数指定确切的模板参数,可能就像:

transform(data.begin(), data.end(), back_inserter(values), 
          bind(get<2, int, tuple<int, double> >, _1);

遗憾的是我不知道如何指定模板参数,所以我使用了辅助函数。对不起。