Boost :: tuple Python equivalent of itemgetter?
I have some code that looks like this:
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>);
Unfortunately, the last line doesn't compile - it gives me a message like this:
/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
Basically, to use Python's operator.itemgetter function, I want to do something like this:
transform(data.begin(), data.end(), back_inserter(values), itemgetter(2))
How can I do this with Boost?
+2
user161827
source
to share
1 answer
For this you will need 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);
}
Basically, the function is get2
also unnecessary, but we have to specify exactly the template argument for the function boost::get
, perhaps like:
transform(data.begin(), data.end(), back_inserter(values),
bind(get<2, int, tuple<int, double> >, _1);
I am ashamed that I cannot specify a template argument, so I used a helper function. Excuse me.
0
source to share