3 ms·
Using Facebook's `folly::gen` library [1], you can get it down to: vector<int> squareVec3(const vector<int>& v) { return from(v) | mapped([](int i){
by ajtulloch 13y ago
Using Facebook's `folly::gen` library [1], you can get it down to:
vector<int> squareVec3(const vector<int>& v) {
return from(v) | mapped([](int i){ return i * i; }) | as<vector>();
}
which is pretty slick.
There are a bunch of the usual LINQ/functional operators in
`folly::gen` that are quite nice. As an example, to filter out the odd elements of `v`, you can do
vector<int> squareVecFiltered(const vector<int>& v) {
return from(v)
| filter([](int i){ return i % 2 == 0; })
| mapped([](int i){ return i * i; })
| as<vector>();
}
https://github.com/facebook/folly/tree/master/folly/gen https://github.com/facebook/folly/tree/master/folly/gen
- humanrebar 13y agoThat's cool, but I'd rather not bitwise-or my functional operators together. Something like this would be better: vector<int> squareVecFiltered(const vector<int>& v) { return from(v filter([](int i){ return i % 2 == 0; }), mapped([](int i){ return i * i; }), as<vector>()); }
- stormbrew 13y agoThat is actually really nice.
- pfultz2 13y agoOr using [Linq](https://github.com/pfultz2/Linq https://github.com/pfultz2/Linq): vector<int> squareVec(const vector<int>& v) { return LINQ(from(i, v) select(i*i)) | linq::to_container; } And also filtering out odd elements: vector<int> squareVecFiltered(const vector<int>& v) { return LINQ(from(i, v) where(i % 2 == 0) select(i*i)) | linq::to_container; }