Reputation: 3307
I would like to add certain offset to all the data stored in std::array container:
std::array<double, 256> data;
ReadData(data);
// apply data offset
const double OFFSET = 0.123;
data += OFFSET;
It can be done with e.g. std::for_each and lambda.
std::for_each(data.begin(), data.end(), [=OFFSET](auto& n){ n += OFFSET; });
I was wondering if there is a more elegant, less verbose and efficient way to achieve this.
Upvotes: 3
Views: 581
Reputation: 4010
If you are not strictly bound to std::array
type, you have a choice of other containers that provide overloaded arithmetic operators.
In the standard library there is std::valarray
, where you can write:
std::valarray<double> data(256);
ReadData(data);
data += OFFSET;
If you need more operations, like solving systems of linear equations, interpolating, etc, you can use full linear algebra library, like Eigen. Other choices include boost.ublas, Blaze, Armadillo, MTL4 etc.
Upvotes: 3
Reputation: 5606
I was wondering if there is a more elegant, less verbose and efficient way to achieve this.
std::transform
is in my opinion more elegant that std::for_each
, because it's the right tool for the job (std::for_each
is more generic). It's more verbose than std::for_each
, don't know how about efficiency:
std::transform(data.begin(), data.end(), data.begin(), [=OFFSET](const double n){
return n + OFFSET;
});
Upvotes: 0
Reputation: 65600
Sometimes just writing the loop is clearer than anything else:
for (auto& n : data) n += OFFSET;
Upvotes: 8